Java else-if Ladder
Table of Contents + β
In the last lesson you learned about the Java nested if statement. But life often has more than two outcomes, like a grade of A, B, C, D, or F. For many outcomes, you chain conditions into an else-if ladder.
π€ Why chain conditions?
A plain if-else gives you only two paths. So what about three, four, or ten outcomes?
- Nesting
if-elseinsideif-elseworks, but the code drifts right and gets hard to read. - An else-if ladder lines up several checks one after another.
- Java picks the first one that fits.
Think about grading a score out of 100. Here is the rule.
- 90 or above is an A.
- 80 to 89 is a B.
- 70 to 79 is a C.
- 60 to 69 is a D.
- Below 60 is a fail, F.
That is five outcomes, not two. A single true-or-false split cannot cover it. The ladder tests conditions top to bottom and stops at the first one that is true.
π§© The else-if syntax
An if, then one or more else if blocks, then an optional else at the bottom. else if is just an else whose body is another if. So it is no new keyword. You are chaining tools you already know. Here is the shape.
if (condition1) { // runs if condition1 is true} else if (condition2) { // runs if condition1 was false and condition2 is true} else if (condition3) { // runs if the ones above were false and condition3 is true} else { // runs if none of the above were true}Here is the whole point of this lesson.
- Java checks the conditions top to bottom.
- The moment one is true, it runs that block.
- It skips every block below, even ones that would also be true.
- If none match, the final
elseruns.
So exactly one block runs. Like a queue at a single door: the first matching ticket walks through, then the door closes.
Now the grading example in real code. It reads a score and prints the matching grade letter.
int score = 85;
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");}Walk through it the way Java does, with a score of 85.
score >= 90? No. Move on.score >= 80? Yes. Java prints βGrade: Bβ.- Java stops. The 70, 60, and
elsechecks never run.
The second check is just score >= 80, not score >= 80 && score < 90. You skip the upper bound because:
- You only reach the second check if the first one was false.
- The first being false already means the score is below 90.
- So the ladder has proven the upper bound for you.
Output
Grade: Bπ’ Why order matters
This is the part people get wrong. Java stops at the first true condition, so the order of your checks changes the result. Same conditions, different order, different answer for the same input. Look at this broken version.
int score = 95;
if (score >= 50) { // β loose check first, catches everything System.out.println("Grade: pass (C-ish)");} else if (score >= 90) { // never reached for a 95 System.out.println("Grade: A");} else if (score >= 80) { System.out.println("Grade: B");}A score of 95 deserves an A. But the ladder is upside down:
- The first check is
score >= 50. For 95, that is true. - Java runs that block, prints the wrong thing, and stops.
- The
score >= 90check that would give the A never runs.
Output
Grade: pass (C-ish)This bug is sneaky.
- The code compiles fine and runs fine.
- It just gives a quietly wrong answer, which is the hardest kind to find.
The fix: put the strictest check first, then loosen as you go down.
int score = 95;
if (score >= 90) { // β
strictest check first System.out.println("Grade: A");} else if (score >= 80) { System.out.println("Grade: B");} else if (score >= 50) { System.out.println("Grade: pass");}Now 95 hits the first check, gets its A, and stops.
Put the strictest check first
In an else-if ladder, order your conditions from the most specific or strictest to the most general. For grades, check the highest score first. If you start with the loosest check, it will catch values that belong higher up the ladder, and the stricter checks below will never run.
π° A tax-slab example with output
Many countries calculate income tax in slabs, where each band of income has its own rate. This fits the ladder perfectly: income falls into exactly one ordered band. Here we work out a simplified tax band for a yearly income.
int income = 65000;String band;
if (income <= 20000) { band = "0% (no tax)";} else if (income <= 50000) { band = "10% slab";} else if (income <= 100000) { band = "20% slab";} else { band = "30% slab";}
System.out.println("Income: " + income);System.out.println("Tax band: " + band);Trace it for an income of 65000.
income <= 20000? No. Skip.income <= 50000? No. Skip.income <= 100000? Yes.bandbecomes β20% slabβ.- Java stops. The final
elsefor top earners never runs.
The direction flipped here:
- Grades checked top down with
>=. - Tax slabs check bottom up with
<=. - Both are fine. Each check assumes the ones above failed, so you still need only one bound per band.
Output
Income: 65000Tax band: 20% slabπ A discount-tier example
An online store gives a bigger discount the more you spend. Same ladder idea, used for a shopping cart.
double cartTotal = 120.0;double discount;
if (cartTotal >= 200) { discount = 0.20; // 20% off for big spenders} else if (cartTotal >= 100) { discount = 0.10; // 10% off} else if (cartTotal >= 50) { discount = 0.05; // 5% off} else { discount = 0.0; // no discount}
double finalPrice = cartTotal * (1 - discount);System.out.println("You pay: " + finalPrice);A cart total of 120 fails the 200 check, passes the 100 check, so it gets 10% off. Java stops. The final price is 120 minus 10%, which is 108.
Output
You pay: 108.0The highest spend stays at the top. So a shopper spending 250 correctly gets the 20% tier, not the 10% one. Order doing the work again.
π¦ Strings in a ladder
A ladder works with any true-or-false condition, including text. Here a traffic light reads a colour and prints what to do.
String light = "yellow";
if (light.equals("red")) { System.out.println("Stop");} else if (light.equals("yellow")) { System.out.println("Slow down");} else if (light.equals("green")) { System.out.println("Go");} else { System.out.println("Unknown light");}Key points for this one:
- Use
.equals()to compare strings. Never use==for text in Java. - Java checks βredβ (false), then βyellowβ (true), so it prints βSlow downβ.
- The final
elseis a safety net for a typo like βyelowβ, so the code does something instead of nothing.
Output
Slow downThis is a good moment to mention switch.
- When every check is βis this variable equal to a fixed value?β,
switchcan be cleaner than a long ladder of.equals()calls. - But ranges like
score >= 90cannot use a basic switch. - So the ladder stays the right tool for ranges. We cover switch in the next lesson.
β οΈ Common Mistakes
A few slip-ups trip up almost everyone at first.
Wrong order of conditions. A loose check placed first grabs values meant for stricter checks below, so those never run.
// β Loose check first, so a 95 wrongly gets "C"if (score >= 70) { System.out.println("C");} else if (score >= 90) { System.out.println("A"); // never reached}
// β
Strictest first, so a 95 correctly gets "A"if (score >= 90) { System.out.println("A");} else if (score >= 70) { System.out.println("C");}Overlapping ranges the ladder already handles. Over-writing the conditions makes the bounds easy to get wrong.
// β Over-complicated and easy to break (notice the gap: what about exactly 80?)if (score >= 90) { System.out.println("A");} else if (score >= 80 && score < 89) { // 89 and 90-edge cases get fumbled System.out.println("B");}
// β
Let the ladder prove the upper bound for youif (score >= 90) { System.out.println("A");} else if (score >= 80) { // already known to be below 90 System.out.println("B");}Using separate ifs instead of else if. Each plain if is checked on its own, so more than one block can run. The ladder is exclusive; separate ifs are not.
// β Separate ifs, both run for a 95if (score >= 90) { System.out.println("A"); }if (score >= 80) { System.out.println("B"); } // also prints!
// β
else if chains them, so only one runsif (score >= 90) { System.out.println("A");} else if (score >= 80) { System.out.println("B");}Forgetting the final else. Without it, if nothing matches, nothing happens. A value can slip through silently, leaving you wondering why nothing printed. Add an else as a catch-all so unexpected input is handled on purpose.
β Best Practices
- Order from strictest to loosest. Check the highest or most specific condition first. This one habit prevents most ladder bugs.
- Use
else if, not separate ifs. It makes the choices exclusive, so exactly one block runs. - Let the ladder prove the bounds. Write
score >= 80, notscore >= 80 && score < 90. Less code, fewer mistakes. - Add a final else. It handles every case you did not list and stops values slipping through unnoticed.
- Keep each block short. If a branch grows large, move its work into a separate method.
- Reach for switch when it fits. Checking one variable against many fixed values reads cleaner as a
switch(next lesson).
π§© What Youβve Learned
You can handle many outcomes now. Quick recap.
- β The else-if ladder chains several conditions to handle more than two outcomes.
- β Java checks the conditions top to bottom and runs the first one that is true, then stops.
- β Order matters: put the strictest condition first, or a loose one will catch values meant for stricter checks.
- β
Each
else ifassumes the checks above it failed, so you only need one bound per band. - β
A final
elseis a catch-all for everything that did not match. - β
Use
else if, not separate ifs, so only one block runs. - β
Ladders handle ranges; for one variable against fixed values, a
switchis often cleaner.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
In an else-if ladder, how many blocks run?
Why: Java checks top to bottom and runs the first true block, skipping the rest.
- 2
Why does order matter in an else-if ladder?
Why: Since Java stops at the first true condition, a loose check placed first will grab values that belong to stricter checks below.
- 3
What does the final else do?
Why: The final else runs only when none of the if or else if conditions were true.
- 4
What is wrong with using several separate if statements instead of else if?
Why: Separate ifs are each checked independently, so more than one can run. else if makes them exclusive.
π Whatβs Next?
When you are checking one variable against many fixed values, there is a cleaner tool: the switch statement. Letβs finish the module with it.