Yes, an If...Else statement can have multiple conditions in Java using the else if clause. The else if clause allows the program to test multiple conditions and execute different blocks of code based on the outcome of those conditions.
The syntax of an If...Else statement with else if clauses is as follows:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else if (condition3) {
// code to be executed if condition3 is true
} else {
// code to be executed if all conditions are false
}
Here, the program first evaluates condition1. If it is true, the program executes the code inside the first if block. If it is false, the program evaluates condition2. If condition2 is true, the program executes the code inside the first else if block. If condition2 is false, the program evaluates condition3, and so on until all conditions have been evaluated.
To understand how an If...Else statement with else if clauses works in Java, consider the following example:
int x = 5;
if (x < 0) {
System.out.println("x is negative");
} else if (x == 0) {
System.out.println("x is zero");
} else if (x < 10) {
System.out.println("x is a single-digit positive number");
} else {
System.out.println("x is a two-digit or larger positive number");
}
In this example, the program first evaluates if x is less than 0. Since x is not negative, the program evaluates if x is equal to 0. Since x is not equal to 0, the program evaluates if x is less than 10. Since x is less than 10, the program executes the code inside the third else if block, which prints the message "x is a single-digit positive number" to the console.
In summary, an If...Else statement with else if clauses allows the program to test multiple conditions and execute different blocks of code based on the outcome of those conditions. If one condition is true, the program executes the corresponding block of code and skips the rest. If all conditions are false, the program executes the code inside the else block.