In Java, if, else if, and short-hand if-else are used to control the flow of a program based on conditions. These structures help us make decisions and execute code accordingly. Let’s explore their usage with practical examples for better understanding.
The if
Statement
The if
statement is the simplest decision-making statement in Java. It checks a condition, and if the condition is true, it executes the block of code inside.
Syntax
if (condition) {
// Code to execute if the condition is true
}
Example 1: Check Positive Number
public class PositiveNumberCheck {
public static void main(String[] args) {
int number = 10;
if (number > 0) {
System.out.println("The number is positive.");
}
}
}
Output:
The number is positive.
Example 2: Check if Eligible for Voting
public class VotingEligibility {
public static void main(String[] args) {
int age = 20;
if (age >= 18) {
System.out.println("You are eligible to vote.");
}
}
}
Output:
You are eligible to vote.
The else if
Statement
When multiple conditions need to be checked, we use else if
. It allows us to evaluate several conditions in sequence.
Syntax
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if none of the conditions are true
}
Example 3: Grading System
public class GradeCalculator {
public static void main(String[] args) {
int marks = 85;
if (marks >= 90) {
System.out.println("Grade: A+");
} else if (marks >= 75) {
System.out.println("Grade: A");
} else if (marks >= 60) {
System.out.println("Grade: B");
} else {
System.out.println("Grade: C");
}
}
}
Output:
Grade: A
Example 4: Temperature Check
public class TemperatureCheck {
public static void main(String[] args) {
int temperature = 30;
if (temperature > 35) {
System.out.println("It's too hot!");
} else if (temperature >= 20 && temperature <= 35) {
System.out.println("The weather is pleasant.");
} else {
System.out.println("It's cold outside.");
}
}
}
Output:
The weather is pleasant.
Short Hand If-Else (Ternary Operator)
The ternary operator is a compact way to write simple if-else statements. It uses the syntax:
variable = (condition) ? valueIfTrue : valueIfFalse;
Example 5: Check Even or Odd
public class EvenOddCheck {
public static void main(String[] args) {
int number = 7;
String result = (number % 2 == 0) ? "Even" : "Odd";
System.out.println("The number is " + result + ".");
}
}
Output:
The number is Odd.
Example 6: Find the Maximum of Two Numbers
public class FindMaximum {
public static void main(String[] args) {
int a = 15;
int b = 20;
int max = (a > b) ? a : b;
System.out.println("The maximum value is " + max + ".");
}
}
Output:
The maximum value is 20.
Real-Time Examples
Example 7: Traffic Light Decision
public class TrafficLight {
public static void main(String[] args) {
String light = "green";
if (light.equals("red")) {
System.out.println("Stop!");
} else if (light.equals("yellow")) {
System.out.println("Get ready to stop.");
} else if (light.equals("green")) {
System.out.println("Go!");
} else {
System.out.println("Invalid light signal.");
}
}
}
Output:
Go!
Example 8: Login Validation
public class LoginValidation {
public static void main(String[] args) {
String username = "admin";
String password = "password123";
if (username.equals("admin") && password.equals("password123")) {
System.out.println("Login successful.");
} else {
System.out.println("Login failed. Incorrect username or password.");
}
}
}
Output:
Login successful.
Example 9: Discount Calculation
public class DiscountCalculator {
public static void main(String[] args) {
int purchaseAmount = 1200;
double discount;
if (purchaseAmount > 1000) {
discount = 0.1; // 10% discount
} else {
discount = 0.05; // 5% discount
}
double totalDiscount = purchaseAmount * discount;
System.out.println("Total discount: $" + totalDiscount);
}
}
Output:
Total discount: $120.0
Example 10: Nested If Example
public class NestedIfExample {
public static void main(String[] args) {
int age = 25;
boolean hasDrivingLicense = true;
if (age >= 18) {
if (hasDrivingLicense) {
System.out.println("You can drive.");
} else {
System.out.println("Get a driving license first.");
}
} else {
System.out.println("You are not old enough to drive.");
}
}
}
Output:
You can drive.
By mastering if, else if, and short-hand if-else, you can make your programs smarter and more dynamic. Try out these examples, and let your creativity build real-world solutions!