2.3 Iteration Constructs, Loop Control, and Branching Labels

Key Takeaways

  • The standard for loop header consists of initialization, termination condition, and update steps; multiple comma-separated variables may be initialized provided they all share the exact same data type.

  • The enhanced for-each loop traverses arrays and java.lang.Iterable objects; it cannot modify primitive array elements in place or structurally modify collections during iteration.

  • while loops evaluate their condition prior to the first iteration, whereas do-while loops execute their body at least once and must terminate with a trailing semicolon.

  • Java strictly forbids unreachable statements at compile time: the body of while (false) and any statement after an infinite loop with no break are compile errors, whereas if (false) is permitted for conditional compilation.

  • Labeled break terminates the designated labeled block or loop, while labeled continue skips the remainder of the current iteration and jumps to the update step of the designated labeled loop.

Last updated: October 2026

2.3 Iteration Constructs, Loop Control, and Branching Labels

Iteration constructs enable repetitive execution of statements until a termination condition is satisfied. Java SE 17 offers four primary loop constructs: the classic for loop, the enhanced for-each loop, the while loop, and the do-while loop. Navigating these constructs on the 1Z0-829 exam requires a precise understanding of header evaluation order, multi-variable initialization constraints, reachability analysis rules, and labeled flow control across nested loops.


The Classical for Loop Architecture

The standard for loop organizes iteration logic into three header expressions separated by semicolons:

for (initialization; terminationCondition; updateExpression) {
    // Loop body
}

Execution Cycle

The Java Virtual Machine executes a standard for loop in a strict sequence:

  1. Initialization: Executes exactly once when entering the loop.
  2. Termination Condition: Evaluated before each iteration. If true, the body executes; if false, the loop terminates.
  3. Loop Body: Executes.
  4. Update Expression: Executes after the body finishes, immediately before the next condition check.
  5. Cycle: Steps 2 through 4 repeat until the condition evaluates to false.

Multi-Variable Declarations and Syntax Rules

The initialization section allows declaring multiple variables separated by commas, but all declared variables must share the same type specifier:

// Legal: i and j are both int
for (int i = 0, j = 10; i < j; i++, j--) {
    System.out.println(i + ":" + j);
}

// COMPILE ERROR: cannot declare variables of different types in for header
// for (int i = 0, long j = 10; i < 5; i++) { }

If variables of differing types must be used, they must be declared prior to the loop header:

int a = 0;
long b = 100L;
for (; a < 5; a++, b += 10) { // Legal: already declared
    System.out.println(a + " - " + b);
}

Optional Header Sections and Infinite Loops

All three components of the for loop header are optional:

  • Omitting the condition causes it to default to true.
  • The statement for (;;) { } creates an infinite loop identical to while (true) { }.

Variables declared in the initialization section have local block scope limited strictly to the header and body of the for loop. Attempting to access an initialized variable after the closing brace of the loop produces a compile-time error.


Enhanced for-each Loop Semantics and Traversal Constraints

Introduced in Java 5, the enhanced for loop simplifies sequential traversal over arrays and collections:

for (ElementType variable : expression) {
    // Loop body
}

Target Requirements

The expression on the right-hand side of the colon must evaluate to:

  1. A Java array (T[]).
  2. An object implementing java.lang.Iterable<T> (such as List, Set, or Queue).

Passing an arbitrary object or a java.util.Map directly to a for-each loop causes a compilation error (though iterating over map.keySet(), map.values(), or map.entrySet() is valid).

Mutation Limitations and Traps

  1. Primitive Array Modification: The loop variable holds a copy of the current array element, not a reference to the array memory slot. Reassigning the loop variable does not modify the array:
int[] numbers = {1, 2, 3};
for (int n : numbers) {
    n = n * 10; // Modifies local variable n only
}
System.out.println(numbers[0]); // Prints 1, NOT 10!
  1. Structural Collection Modification: Altering the structure of a collection (invoking add(), remove(), or clear()) while iterating via an enhanced for loop throws java.util.ConcurrentModificationException at runtime:
List<String> names = new ArrayList<>(List.of("Alice", "Bob", "Charlie"));
for (String name : names) {
    if (name.equals("Alice")) {
        names.remove(name); // Throws ConcurrentModificationException on the next iteration!
    }
}

Warning

The exception is thrown by the iterator's next next() call, not by remove(). If the removed element is the second-to-last one (for example, removing "Bob" from this three-element list), hasNext() returns false immediately and the loop ends silently without an exception, leaving [Alice, Charlie]. Use Iterator.remove() or removeIf() instead.


while vs. do-while Loops

The while and do-while loops differ primarily in the timing of condition evaluation:

// Pre-test loop: condition checked before first iteration
int count = 10;
while (count < 5) {
    System.out.println("Never runs");
}

// Post-test loop: body guaranteed to execute at least once
int total = 10;
do {
    System.out.println("Executes once");
} while (total < 5); // Note: Trailing semicolon is mandatory!

Warning

Forgetting the trailing semicolon ; after the condition in a do-while construct is a common syntax trap that produces a compilation error.


Reachability Analysis and Unreachable Code Rules

The Java compiler enforces strict reachability rules governed by JLS §14.21. Any statement that cannot be executed under any circumstance causes a compile-time error, rather than a silent runtime omission.

Constant Conditions: while (false) vs. if (false)

A prominent exam topic is the asymmetric treatment of constant false conditions between while loops and if statements:

// Legal: JLS explicitly allows if (false) to support conditional compilation
if (false) {
    System.out.println("Dead code, but compiles");
}

// COMPILE ERROR: unreachable statement
// while (false) {
//     System.out.println("Unreachable");
// }

Unreachable Statements Following Unconditional Transfers

Any statement immediately following an unconditional break, continue, return, or throw in the same block is unreachable and fails compilation:

while (true) {
    break;
    // System.out.println("Hello"); // COMPILE ERROR: unreachable statement
}

However, if an unreachable branch is guarded by a non-constant condition, the compiler allows it:

boolean flag = false;
while (flag) { // Compiles! flag is a variable, not a compile-time constant literal
    System.out.println("Compiles because flag is not final");
}

Branching Statements, Labeled Loops, and Evaluation Order

Java provides three unconditioned branching statements: break, continue, and return.

  • break: Exits the innermost loop or switch construct.
  • continue: Skips the remainder of the current iteration and jumps to the update step (in for) or condition check (in while/do-while).

Labeled Statements for Nested Flow Control

In deeply nested loops, an unlabeled break or continue only affects the innermost loop. Java allows prefixing any statement or loop with an identifier label (e.g., OUTER:).

  1. Labeled break: Terminates the entire statement or loop identified by the label.
  2. Labeled continue: Aborts the current iteration and immediately begins the next iteration of the designated labeled loop.
OUTER:
for (int i = 1; i <= 3; i++) {
    INNER:
    for (int j = 1; j <= 3; j++) {
        if (i == 2 && j == 2) {
            break OUTER; // Exits both loops immediately
        }
        if (j == 1) {
            continue INNER; // Advances j to 2
        }
        System.out.print(i + "" + j + " ");
    }
}
// Outputs: 12 13 

Evaluation Order in Loop Conditions with Side Effects

On the 1Z0-829 exam, loop conditions often contain increment (++) or decrement (--) operators:

int x = 0;
while (x++ < 3) {
    System.out.print(x + " ");
}

Tracing the evaluation:

  1. x = 0: Condition evaluates 0 < 3 (true), then x increments to 1. Body prints "1 ".
  2. x = 1: Condition evaluates 1 < 3 (true), then x increments to 2. Body prints "2 ".
  3. x = 2: Condition evaluates 2 < 3 (true), then x increments to 3. Body prints "3 ".
  4. x = 3: Condition evaluates 3 < 3 (false), then x increments to 4. Loop exits.
  5. Final value of x after the loop is 4. Total output: "1 2 3 ".

Comparison of Java Iteration Constructs

FeatureStandard forEnhanced for-eachwhiledo-while
Minimum Executions0001
Condition Check TimingBefore each iterationBefore each elementBefore each iterationAfter each iteration
Index AccessDirect counter availableNo built-in index counterManual counter neededManual counter needed
Target ApplicabilityAny conditional loopArrays & Iterable onlyAny conditional loopAny conditional loop
Header VariablesMultiple of same typeSingle element variableNone declared in headerNone declared in header
Trailing SemicolonNoNoNoYes (mandatory after while(...))
Test Your Knowledge

What is the output of the following nested loop construct?

public class LabeledFlow {
    public static void main(String[] args) {
        int count = 0;
        ROW_LOOP:
        for (int r = 1; r <= 3; r++) {
            COL_LOOP:
            for (int c = 1; c <= 3; c++) {
                if (r == c) {
                    continue ROW_LOOP;
                }
                count++;
            }
        }
        System.out.println(count);
    }
}
A

6

B

0

C

3

D

2

Test Your Knowledge

Consider the following two code segments:

// Segment 1
if (false) {
    System.out.println("One");
}

// Segment 2
while (false) {
    System.out.println("Two");
}

What happens when attempting to compile these two segments?

A

Segment 1 compiles successfully, but Segment 2 produces a compile-time error

B

Both Segment 1 and Segment 2 compile successfully because Java permits unreachable code in dead blocks

C

Segment 2 compiles successfully, but Segment 1 produces a compile-time error

D

Neither Segment 1 nor Segment 2 compiles because unreachable code produces a compiler error

Test Your Knowledge

Given the following program:

public class LoopHeaderTest {
    public static void main(String[] args) {
        for (int i = 0, long j = 10; i < j; i++) {
            System.out.println(i);
        }
    }
}

What is the result of attempting to compile and run this code?

A

The code compiles and prints numbers 0 through 9

B

The code compiles and prints 0 followed by an ArithmeticException

C

The code fails to compile because i < j compares an int with a long

D

Compilation fails: for-loop header variables must share one type

Test Your Knowledge

What is the output of the following do-while program?

public class DoWhileEvaluation {
    public static void main(String[] args) {
        int x = 5;
        do {
            System.out.print(x + " ");
        } while (x++ < 5);
        System.out.print(x);
    }
}
A

5 5

B

5 5 6

C

The code produces an infinite loop printing 5

D

5 6

Sections you finish are checked off in the contents.