else if Chains
Handle multiple mutually exclusive conditions in sequence using else if to create a decision chain.
Overview
Key Points
- •else if chains are evaluated top-to-bottom; the first true condition wins
- •At most ONE block in an if/else-if/else chain will execute
- •A final else (no condition) acts as a default catch-all for all other cases
- •Order matters: if conditions overlap, earlier conditions shadow later ones
- •Very long else-if chains on a single value (like a day number) are better written as switch
- •Each condition is only checked if all previous conditions were false
Examples
Grade classification with else if
public class Main {
public static void main(String[] args) {
int score = 78;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else if (score >= 60) {
System.out.println("Grade: D");
} else {
System.out.println("Grade: F");
}
}
}Score 78 matches score >= 70 (Grade C). All conditions below that are skipped.
Ordering matters - specific conditions before general
public class Main {
public static void main(String[] args) {
int x = 15;
// CORRECT: most specific first
if (x > 20) {
System.out.println("Greater than 20");
} else if (x > 10) {
System.out.println("Greater than 10"); // ← matches x=15
} else {
System.out.println("10 or less");
}
// WRONG ORDER: general condition catches everything
if (x > 10) { // ← matches x=15 first
System.out.println("Greater than 10");
} else if (x > 20) { // ← never reached when x=15
System.out.println("Greater than 20");
}
}
}If you put the broad condition (x > 10) before the narrow one (x > 20), the narrow one can never be reached.
Season classifier
public class Main {
public static void main(String[] args) {
int month = 4; // April
String season;
if (month == 12 || month <= 2) {
season = "Winter";
} else if (month <= 5) {
season = "Spring";
} else if (month <= 8) {
season = "Summer";
} else {
season = "Autumn";
}
System.out.println("Month " + month + ": " + season);
}
}else if is clean for range-based classification when values do not overlap.
Common Mistakes
- Missing the else catch-all: if all conditions are false and there's no else, the variable may be uninitialised
- Redundant conditions: `if (x >= 90) ... else if (x >= 80 && x < 90) ...` - the second condition can never reach x >= 90 since the first already checked that, so `x < 90` is redundant
- Very deep else-if chains (10+) - switch statement is cleaner for exact-value matching
Note
If an else-if chain assigns a value to a variable, consider using a single-line ternary or a lookup structure (array/Map) for very simple cases. But for clarity, an else-if chain with 3–6 branches is perfectly readable.
Exercises
Write Java code and click Run to execute it instantly. When your output looks correct, mark as done.
Completed: 0 / 4 exercises
Knowledge Check
Question 1 of 4