The else if Ladder: Multiple Conditions
What you'll learn: How to test multiple mutually exclusive conditions in a clear, readable sequence using else if.
The Core Idea
Sometimes you need to choose between more than two options. The if-else structure works great for binary choices, but what if you're checking a student's grade (A, B, C, D, or F) or determining which season it is based on a month? This is where the else if ladder comes in.
An else if ladder lets you chain together multiple conditions that Java checks one at a time, from top to bottom. As soon as one condition evaluates to true, Java executes that block and skips all remaining conditions—even if they would also be true.
The Pattern
if (condition1) {
// executed if condition1 is true
} else if (condition2) {
// executed if condition1 is false AND condition2 is true
} else if (condition3) {
// executed if condition1 and condition2 are false AND condition3 is true
} else {
// executed if none of the above conditions are true
}
Think of It Like...
Imagine a security checkpoint with multiple gates. You approach the first gate; if you meet its requirement, you pass through and skip all other gates. If not, you move to the second gate, then the third, and so on. Only one gate lets you through.
Example
int score = 85;
if (score >= 90) {
// not executed (85 < 90)
} else if (score >= 80) {
// executed! (85 >= 80)
} else if (score >= 70) {
// skipped, even though 85 >= 70
} else {
// skipped
}
Key Takeaway: Use the else if ladder to evaluate multiple mutually exclusive conditions in sequence; Java stops at the first true condition and skips the rest.