Nested if Statements
| English | Chinese | Pinyin |
|---|---|---|
| nested if | 嵌套 if | qiàn tào if |
An if inside an if
- A nested if 嵌套 if puts one
ifstatement inside another's block. - The inner condition is only checked when the outer one is
true. - "If it's a weekday, then if it's raining, take an umbrella."
- Nesting expresses decisions that depend on earlier decisions.
The else-if ladder
- Chaining
else ifhandles several exclusive cases in order. if (s >= 90) A; else if (s >= 80) B; else if (s >= 70) C; else F;- Java checks each condition top to bottom and takes the first true one.
- Once a branch runs, the rest of the ladder is skipped.
Order matters
- In an
else ifladder, put the most specific / highest conditions first. s >= 70would catch a95too — sos >= 90must come before it.- If a broad condition comes first, later narrower ones can never run.
- Reading top to bottom, the first match wins.
Tracing nested logic
- Trace outer-first: evaluate the outer condition, then step inside only if it's true.
- For a ladder, test each condition in order until one is
true. - Exactly one final branch runs (the first match, or the final
else). - Draw the path with the actual values to avoid mistakes.
In an else if ladder, order is everything — the FIRST true condition wins and the rest are skipped. If you write if (s >= 60) … else if (s >= 90) …, the >= 90 branch is unreachable (any s >= 90 already satisfied >= 60). Put the tightest conditions first.
A grade ladder:
if (s >= 90) "A"; else if (s >= 80) "B"; else if (s >= 70) "C"; else "F";s = 85→>= 90? no →>= 80? yes → "B" (stop).- The
>= 70andelseare never checked.
A nested if puts an if inside another block; the inner condition is tested only when the outer is true. An else if ladder takes the first true condition top to bottom, then skips the rest — so order matters: put the tightest conditions first, or later ones become unreachable.
The first true branch wins
s = 85 takes the >= 80 branch (B); later branches are skipped.
In an else-if ladder, which condition's block runs?
Java takes the first true condition top to bottom.
For if (s>=90) A; else if (s>=80) B; else C; with s = 85, the result is...
85 fails >=90 but passes >=80 → B, then stop.
If a broad condition comes before a narrower one in a ladder, the narrower branch can become unreachable.
The broad condition catches those cases first; put tightest first.
In a nested if, the inner condition is checked even when the outer condition is false.
The inner if is only reached when the outer condition is true.
In an else-if ladder, the conditions should generally be ordered...
First match wins, so specific conditions must come first.