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.
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:
- Initialization: Executes exactly once when entering the loop.
- Termination Condition: Evaluated before each iteration. If
true, the body executes; iffalse, the loop terminates. - Loop Body: Executes.
- Update Expression: Executes after the body finishes, immediately before the next condition check.
- 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 towhile (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:
- A Java array (
T[]). - An object implementing
java.lang.Iterable<T>(such asList,Set, orQueue).
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
- 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!
- Structural Collection Modification: Altering the structure of a collection (invoking
add(),remove(), orclear()) while iterating via an enhancedforloop throwsjava.util.ConcurrentModificationExceptionat 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 (infor) or condition check (inwhile/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:).
- Labeled
break: Terminates the entire statement or loop identified by the label. - 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:
x = 0: Condition evaluates0 < 3(true), thenxincrements to1. Body prints"1 ".x = 1: Condition evaluates1 < 3(true), thenxincrements to2. Body prints"2 ".x = 2: Condition evaluates2 < 3(true), thenxincrements to3. Body prints"3 ".x = 3: Condition evaluates3 < 3(false), thenxincrements to4. Loop exits.- Final value of
xafter the loop is4. Total output:"1 2 3 ".
Comparison of Java Iteration Constructs
| Feature | Standard for | Enhanced for-each | while | do-while |
|---|---|---|---|---|
| Minimum Executions | 0 | 0 | 0 | 1 |
| Condition Check Timing | Before each iteration | Before each element | Before each iteration | After each iteration |
| Index Access | Direct counter available | No built-in index counter | Manual counter needed | Manual counter needed |
| Target Applicability | Any conditional loop | Arrays & Iterable only | Any conditional loop | Any conditional loop |
| Header Variables | Multiple of same type | Single element variable | None declared in header | None declared in header |
| Trailing Semicolon | No | No | No | Yes (mandatory after while(...)) |
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);
}
}
6
0
3
2
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?
Segment 1 compiles successfully, but Segment 2 produces a compile-time error
Both Segment 1 and Segment 2 compile successfully because Java permits unreachable code in dead blocks
Segment 2 compiles successfully, but Segment 1 produces a compile-time error
Neither Segment 1 nor Segment 2 compiles because unreachable code produces a compiler error
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?
The code compiles and prints numbers 0 through 9
The code compiles and prints 0 followed by an ArithmeticException
The code fails to compile because i < j compares an int with a long
Compilation fails: for-loop header variables must share one type
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);
}
}
5 5
5 5 6
The code produces an infinite loop printing 5
5 6
Sections you finish are checked off in the contents.