Topic 2.4 — Nested if Statements
Goal: trace and write nested if statements, and understand how the structure of nesting affects which blocks run.
The big idea
A nested if is an if statement inside another if (or inside an else block).
Nesting lets your code make a second decision only after a first decision is made.
Rule: always evaluate conditions from the outside in.
Why nesting exists
- You want to check a “big” condition first, then only do extra checks if it passes.
- You want multi-step decisions (like login → then permissions).
- You need logic like “if A is true, then check B; otherwise do something else.”
Nested if inside if
int score = 85;
boolean didProject = true;
if (score >= 70) {
if (didProject) {
result = "pass";
} else {
result = "incomplete";
}
} else {
result = "retry";
}
The inner if only runs if score >= 70.
Nested if inside else
Sometimes you nest because you only want extra checks in the “failed” case.
if (x >= 0) {
type = "nonnegative";
} else {
if (x % 2 == 0) {
type = "negative even";
} else {
type = "negative odd";
}
}
The “dangling else” rule (super tested)
An else always matches the closest unmatched if.
This can surprise people when braces are missing.
Risky (no braces)
if (a)
if (b)
x = 1;
else
x = 2;
The else matches if (b), not if (a).
Clear (with braces)
if (a) {
if (b) {
x = 1;
} else {
x = 2;
}
}
Same logic, but now there’s no ambiguity.
Nesting vs. compound conditions
Sometimes you can replace nesting with && or ||… but not always.
| Approach | When it’s good |
|---|---|
| Nesting | When the second check should only happen after the first is true |
| Compound condition | When you can express the decision as one boolean expression |
Common mistakes
- Missing braces causes the
elseto attach to the wrongif. - Tracing incorrectly: you must re-check which blocks actually run.
- Over-nesting when a simple compound condition would be clearer.
Exam mindset
- Trace from the outside in. If the outer condition is false, inner blocks don’t run.
- Assume
elsematches the nearest unmatchedifunless braces force otherwise. - Braces make logic unambiguous—AP questions often test what happens without them.
Quick self-check
- What does “nested if” mean?
- When does the inner
ifrun? - In code without braces, which
ifdoes anelsematch? - Why might nesting be safer than a compound condition sometimes?
- Why do braces matter even if the logic is “simple”?