1. University MCA (AI/ML) Semester 2
  2. CAP477
  3. Unit 1

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 switch falls through to the next case unless break is used. With d = 2 and cases 1, 2, 3 printing without breaks until case 3, the output is two 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 else binds to the nearest if.
  • switch accepts byte, short, char, int, their wrappers, String and enums (not long, float, double, boolean).

Loops:

LoopTestRuns at least once
for (init; cond; update)beforeNo
while (cond)beforeNo
do { } while (cond);afterYes
for-each for (T x : coll)n/aNo

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

Question 1 · Tier 1, Recall

Which loop is guaranteed to execute its body at least once?

  1. while
  2. for
  3. do-while
  4. for-each
Show the answer

C. The condition of do-while is tested after the body.

Question 2 · Tier 4, Analyse

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:

  1. 9
  2. 4
  3. 6
  4. 2
Show the answer

B. i = 0 and i = 1 each count j = 0 and 1, then i = 2 breaks: 4.