if…else if Statement
The if...else if
statement in Java allows you to handle multiple conditions in a sequence. It's an extension of the basic if...else
statement and is useful when you have more than two possible outcomes based on the evaluation of different conditions.
Example:
public class IfElseIfStatementExample {
public static void main(String[] args) {
int num = 0;
if (num > 0) {
System.out.println("Number is positive");
} else if (num < 0) {
System.out.println("Number is negative");
} else {
System.out.println("Number is zero");
}
}
}
In this example:
- The
if
statement checks ifnum
is greater than 0 and prints a message if true. - The
else if
statement checks ifnum
is less than 0 and prints a different message if true. - The
else
block is executed only if both theif
andelse if
conditions are false.
You can have multiple else if
blocks to check additional conditions. The if...else if
statement provides a structured way to handle multiple conditions without nesting multiple if...else
statements, improving code readability and maintainability.