CAP477 · Unit 1: Java fundamentals
Control flow: conditions, switch and loops
8 practice questions
Key points
- switch falls through without break
- do-while runs at least once
- break/continue can use labels
- Dangling else attaches to the nearest if
Selection: if / else if / else, ternary ?:, and switch.
- A classic
switchfalls through to the next case unlessbreakis used. Withd = 2and cases 1, 2, 3 printing without breaks until case 3, the output istwo three. - Java 14+ switch expressions use arrows and need no
break:int n = switch (day) { case "MON", "TUE" -> 1; case "SAT" -> 2; default -> 0; }; - A dangling
elsebinds to the nearestif. switchaccepts byte, short, char, int, their wrappers,Stringand enums (not long, float, double, boolean).
Loops:
| Loop | Test | Runs at least once |
|---|---|---|
for (init; cond; update) | before | No |
while (cond) | before | No |
do { } while (cond); | after | Yes |
for-each for (T x : coll) | n/a | No |
break leaves the loop; continue skips to the next iteration. Labels let them target an outer loop: continue outer; or break outer;. for (;;) is an infinite loop. A stray ; after for (...) makes an empty body.
Traces (verified): summing odd numbers up to 7 with continue and break gives 16; a do-while with a false condition still runs once; for (int j = 10; j > 0; j /= 2) runs 4 times.
Exam pitfall: forgetting break in a classic switch prints extra lines.
Try two questions
Which loop is guaranteed to execute its body at least once?
- while
- for
- do-while
- for-each
Show the answer
C. The condition of do-while is tested after the body.
outer: for i in 0..2 { for j in 0..2 { if (j == 2) continue outer; if (i == 2) break outer; cnt++; } } (cnt starts at 0). The final cnt is:
- 9
- 4
- 6
- 2
Show the answer
B. i = 0 and i = 1 each count j = 0 and 1, then i = 2 breaks: 4.