Nested if Statements
Multiway Selection with else if
Chain else if to pick between three or more paths — only the first true branch runs:
if (distance < 1.0)
{
state = IntakeState.CLOSE;
}
else if (distance < 3.0)
{
state = IntakeState.MID;
}
else
{
state = IntakeState.FAR;
}
A trailing plain else (no condition) catches everything not already matched — it's optional, but leaving it off means "do nothing" is a real possible outcome.
Chained vs. Separate ifs
else if connects the branches together — only one of them ever runs. Writing separate, unconnected if statements instead is a different (and often wrong) thing entirely, because all of them get checked independently:
// Connected — only one branch runs
if (score >= 90) { grade = "A"; }
else if (score >= 80) { grade = "B"; }
else { grade = "C"; }
// NOT connected — multiple could run, overwriting each other
if (score >= 90) { grade = "A"; }
if (score >= 80) { grade = "B"; } // a 95 would hit this too, overwriting "A" with "B"!
The Dangling Else
When ifs are nested without braces, an else always attaches to the closest unmatched if — regardless of indentation. If that's not what you meant, braces fix it:
if (sunny)
{
if (hot)
{
goToBeach();
}
}
else // now belongs to the OUTER if, thanks to the braces
{
bringUmbrella();
}
Common Pitfalls
- Using separate
ifs instead ofelse if. Separate ifs are each checked independently — a later one can silently overwrite what an earlier one just set. - Relying on indentation instead of braces. Java ignores indentation entirely; only
{ }actually determines whichifanelsebelongs to. - Skipping the trailing
elsewhen a local variable is only assigned inside branches. Java requires a local variable to be definitely assigned before it's read — if no branch is guaranteed to run, the compiler won't let you read it afterward:
String tier; // local variable, no initial value
if (score >= 8)
{
tier = "ELITE";
}
// no else — if score < 8, tier is never assigned
System.out.println(tier); // won't compile: tier might not be assigned
This only applies to local variables — an instance variable like state above already has a default value, so it doesn't need every branch to cover it.
Key Takeaways
else ifchains pick exactly one branch — the first condition that's true, and nothing after it.- Unconnected, separate
ifstatements are checked independently and can overwrite each other's results. - An
elsealways attaches to the nearest unmatchedif— braces are the only reliable way to control this.
Derived from csawesome-2026: unit-2-selection-and-iteration/2.04-nested-if-statements.md (CSA 2.4)