Java else if statement
Created By: chatGPT
In Java, the
else if
statement is used to specify a new condition if the previous if
statement evaluates to false. This allows for multiple conditions to be tested sequentially. The syntax consists of the if
statement followed by one or more else if
statements and an optional else
statement. Here's how it works:if (condition1) {
// code block executed if condition1 is true
} else if (condition2) {
// code block executed if condition2 is true
} else {
// code block if both condition1 and condition2 are false
}
Let's look at an example where we check a person's age and categorize them as a child, teenager, or adult.
int age = 15;
if (age < 13) {
System.out.println("Child");
} else if (age >= 13 && age < 20) {
System.out.println("Teenager");
} else {
System.out.println("Adult");
}
In this example, if the
age
is less than 13, it prints Child. If the age
is between 13 and 19, it prints Teenager. If neither condition is satisfied, it defaults to printing Adult.int age = 20;
if (age < 13) {
System.out.println("Child");
} else if (age >= 13 && age < 20) {
System.out.println("Teenager");
} else {
System.out.println("Adult");
}
You can add multiple
else if
statements to evaluate more conditions. Here is how you might add a condition for a senior citizen category:int age = 65;
if (age < 13) {
System.out.println("Child");
} else if (age >= 13 && age < 20) {
System.out.println("Teenager");
} else if (age >= 60) {
System.out.println("Senior Citizen");
} else {
System.out.println("Adult");
}
In this modified example, if the
age
is 60 or older, it prints Senior Citizen. This demonstrates how flexible the else if
construct is for evaluating numerous conditions in your Java programs.int age = 45;
if (age < 13) {
System.out.println("Child");
} else if (age >= 13 && age < 20) {
System.out.println("Teenager");
} else if (age >= 60) {
System.out.println("Senior Citizen");
} else {
System.out.println("Adult");
}