Recap
A nested if is an if, if-else or if-else-if inside another. A multiway selection (if-else-if) chooses one of several options.
| Structure | How it runs |
|---|---|
| Nested if | Inner condition evaluated only if the outer condition lets execution reach it |
| if-else-if chain | Conditions tested top to bottom; the first true one runs; the rest are skipped |
| Trailing else | Runs only if every earlier condition was false; optional |
| Separate ifs | Every condition tested; several bodies can run |
Key relationships
| Idea | Rule |
|---|---|
| Bodies that can run in a chain | At most one |
| Reaching a later condition | All earlier conditions were false |
| Order of overlapping conditions | Most demanding (most specific) first |
| Dangling else | Pairs with the nearest unmatched if; braces fix it |
| Boundary values | Test the exact boundary of each band (<= versus <) |
| Chain versus nest | Same quantity in bands: chain. Dependent second question: nest |
Assumptions
- Conditions in a chain are Boolean expressions evaluated in written order.
- Every path assigns a value to any variable used after the structure, or the code will not compile.
- Braces are used around every body unless stated.
Mistakes to avoid
- Writing the bands in the wrong order, so a low band catches high values.
- Replacing
else ifbyif, so later bodies overwrite earlier ones. - Reading an
elseas belonging to the outerifbecause of indentation. - Forgetting that a nested condition may never be evaluated.
- Using
<when the boundary belongs in the band (or the reverse). - Leaving off the final
elseand leaving a variable unassigned.
Worked mini-example
int t = 18;
String s;
if (t < 0) {
s = "freezing";
} else if (t < 15) {
s = "cold";
} else if (t < 25) {
s = "mild";
} else {
s = "hot";
}
Trace for t = 18: 18 < 0 false; 18 < 15 false; 18 < 25 true, so s = "mild". The hot branch is never reached. For t = 15 the answer is also “mild”, because 15 < 15 is false. For t = -4 the first test is true, so the later tests are never evaluated.
Quick self-check
- In an if-else-if chain of four conditions, how many bodies can run? Answer: at most one.
- If
x = 10, what doesif (x > 5) { r = 1; } else if (x > 8) { r = 2; }setrto? Answer: 1; the second condition is never tested. - When is the inner condition of a nested if evaluated? Answer: only when the outer condition allows execution to reach it.
- In
if (a) if (b) X; else Y;whichifdoes theelsebelong to? Answer: the nearer one,if (b).
Full explanations and diagrams are in the Topic 2.4 study guide.