Skip to content

Lesson 03 · Loops & Branching

Objectives

After this lesson you will be able to:

  • Choose between while, do-while, the classic for, and the enhanced for.
  • Use break and continue, including labeled forms to control nested loops.
  • Avoid the exam's iteration traps: off-by-one, infinite loops, and modifying a collection while iterating it.

while and do-while

A while tests before each iteration (may run zero times); a do-while tests after (runs at least once).

java
int i = 0;
while (i < 3) { System.out.print(i++); }    // 012
int j = 5;
do { System.out.print(j); } while (j < 3);  // 5 — body runs once, then the test fails

Gotcha

A do-while always ends with a semicolon after the condition. Forgetting it is a compile error.

The classic and enhanced for

The classic for has three parts — init, condition, update — any of which may be empty (for (;;) is an infinite loop).

java
for (int k = 0; k < 3; k++) { use(k); }
for (int a = 0, b = 9; a < b; a++, b--) { }   // multiple init/update, comma-separated

The enhanced for (for-each) iterates arrays and any Iterable, with no index:

java
int[] nums = {10, 20, 30};
for (int n : nums) { sum += n; }
for (String s : List.of("a", "b")) { }

Exam trap

The enhanced for gives you a copy of each element reference, not the slot. Assigning to the loop variable does not change the array/collection:

java
for (int n : nums) { n = 0; }    // nums is unchanged — still {10, 20, 30}

break, continue, and labels

break exits the innermost loop or switch; continue skips to the next iteration. A label lets either target an outer loop:

java
outer:
for (int r = 0; r < 3; r++) {
    for (int c = 0; c < 3; c++) {
        if (grid[r][c] == target) {
            found = true;
            break outer;          // exits BOTH loops
        }
    }
}

continue label; jumps to the next iteration of the labeled loop rather than the inner one.

Exam trap

Modifying a collection while iterating it with an enhanced for (or its iterator) throws ConcurrentModificationException. To remove during iteration, use an explicit Iterator and call it.remove(), or Collection.removeIf(...).

java
for (String s : list) { if (s.isBlank()) list.remove(s); }  // ConcurrentModificationException
list.removeIf(String::isBlank);                              // correct

Key Takeaways

  • while tests first (0+ runs); do-while tests last (1+ runs) and needs a trailing semicolon.
  • The classic for has optional init/condition/update; the enhanced for iterates arrays and Iterables without an index but exposes only a copy of each element — assigning to it changes nothing.
  • break/continue act on the innermost loop unless given a label, which targets an enclosing loop.
  • Removing from a collection during a for-each throws ConcurrentModificationException — use Iterator.remove() or removeIf.

Lesson Quiz

Lesson Quiz · Loops & Branching0 / 5
  1. What does this print?

    int j = 5;
    do { System.out.print(j); } while (j < 3);
    • Anothing
    • B5
    • C555…
    • DCompile error
  2. After this loop, what is nums?

    int[] nums = {1, 2, 3};
    for (int n : nums) { n = 0; }
    • A{0, 0, 0}
    • B{1, 2, 3}
    • C{0, 2, 3}
    • DCompile error
  3. What does break outer; do here?

    outer:
    for (...) {
      for (...) {
        break outer;
      }
    }
    • AExits the inner loop only
    • BExits both loops
    • CCompile error
    • DContinues the outer loop
  4. Which safely removes blank strings while iterating?

    • Afor (String s : list) list.remove(s);
    • Blist.removeIf(String::isBlank);
    • Cfor (int i=0;i<list.size();i++) if (list.get(i).isBlank()) list.remove(i);
    • DNone
  5. How many times does the body run?

    for (int i = 0; i < 0; i++) { body(); }
    • A0
    • B1
    • Cinfinite
    • DCompile error

Next: Module 02 Mini-Exam. Run the matching code in labs/src/main/java/com/jse21/m02_flow/Loops.java.