JavaCore java
If else if in Java
Why Use Else If?
- Sometimes we need to check multiple conditions.
if-else-if
ladder allows checking conditions one by one.- Once a true condition is found, its block executes → remaining blocks are skipped.
Syntax
if (condition1) {
// executes if condition1 is true
} else if (condition2) {
// executes if condition2 is true
} else if (condition3) {
// executes if condition3 is true
} else {
// executes if all conditions are false
}
Example – Find the Greatest of Three Numbers
public class Demo {
public static void main(String[] args) {
int x = 8;
int y = 7;
int z = 9;
if (x > y && x > z) {
System.out.println(x);
} else if (y > z) {
System.out.println(y);
} else {
System.out.println(z);
}
}
}
👉 Output: 9
Flow Explanation
-
Check if
x
is greater than bothy
andz
.- If true → print
x
.
- If true → print
-
Else, check if
y
is greater thanz
.- If true → print
y
.
- If true → print
-
Else (remaining case) → print
z
.
Key Notes
- Execution stops at the first true condition.
else
block is optional.- Useful for multi-branch decision making.