7.2 Traditional for and Enhanced for-each Loops

Key Takeaways

  • A basic for loop runs initialization once, then checks the condition before each body entry. The update runs after normal completion or a continue targeting that loop.

  • The initializer can declare multiple variables using one base type, or assign multiple already-declared variables. Brackets after a name may give that variable a different array type.

  • An omitted for condition is treated as true. for (;;) { ... } keeps running until a transfer such as break, return, or throw exits it.

  • The enhanced for-each loop works exclusively on arrays and java.lang.Iterable implementations, never directly on a Map or String

  • Reassigning the for-each loop variable never modifies the underlying array or list element, but calling mutating methods on a referenced heap object such as StringBuilder.append does alter the object

Last updated: November 2026

7.2 Traditional for and Enhanced for-each Loops

Java provides two distinct for constructs: the three-part traditional for loop for index-driven or custom-stepped iteration, and the enhanced for (for-each) loop introduced in Java 5 for clean traversal of arrays and Iterable collections.

Traditional for Loop Execution Order

The traditional for header has three clauses separated by semicolons:

for (initialization; booleanCondition; update) {
    // Loop body
}

The exact execution sequence is strictly ordered:

  1. initialization executes once before the loop starts.
  2. booleanCondition is evaluated. If false, the loop terminates immediately without entering the body.
  3. body executes.
  4. update executes if the body completed normally or transferred control with a continue targeting this loop. A break exiting this loop or a return skips the update.
  5. Control returns to step 2 (booleanCondition).

Consider this trace:

for (int i = 0; i < 3; i++) {
    System.out.print(i + " ");
}
Passi at Conditioni < 3Outputi after Update
10true0 1
21true1 2
32true2 3
43false(loop exits)—

Optional Clauses and for ( ; ; )

All three clauses in a traditional for header are optional, though both semicolons are mandatory. When booleanCondition is omitted, Java treats it as true. Therefore, for ( ; ; ) is a legal infinite loop—equivalent to while (true)—and any statement written immediately after it without a reachable break fails compilation as an unreachable statement.

int k = 0;
for ( ; k < 2; ) {
    System.out.print(k++);
} // Prints 01

Multiple Variables and Comma-Separated Expressions

Java allows multiple comma-separated items in initialization and update, subject to strict rules:

  • Declaring variables in init: The declaration has one base type written at the start. Brackets on individual names can add array dimensions. For instance, for (int i = 0, data[] = {3}; i < data.length; i++) { ... } uses int and int[] with one base type.
  • Reassigning pre-declared variables in init: If variables already exist before the for loop, you may reassign them in init even if their types differ.
  • Valid init and update statements: Both clauses can contain comma-separated expression statements (such as assignments, increments, or method calls like System.out.print(...)).
  • Single booleanCondition: You cannot put comma-separated expressions in the condition clause; it must be a single expression of type boolean or Boolean (combine conditions with && or ||).
// VALID: single shared type 'int'
for (int i = 0, j = 4; i < j; i++, j--) {
    System.out.print(i + "-" + j + " ");
} // Prints: 0-4 1-3

// INVALID: cannot mix types or repeat type keyword
// for (int i = 0, long j = 0; i < 5; i++) { }  // Compile error
// for (int i = 0, int j = 0; i < 5; i++) { }   // Compile error

// VALID: reassigning pre-declared variables of different types
int a;
long b;
for (a = 0, b = 10L; a < 2; a++, b += 5) {
    System.out.print(a + ":" + b + " ");
} // Prints: 0:10 1:15

Loop Variable Scope

A variable declared inside the init clause is in scope in its own initializer, later declarators, the condition, update, and body. Attempting to read it after the loop fails compilation with cannot find symbol. Conversely, you cannot declare a variable in init with the same name as a local variable already in scope in that method:

int x = 10;
// for (int x = 0; x < 3; x++) { } // Compile error: variable x is already defined
for (int y = 0; y < 3; y++) { }
// System.out.println(y);          // Compile error: cannot find symbol 'y'

The Enhanced for-each Loop

The enhanced for loop simplifies sequential traversal without managing an index or Iterator:

for (ElementType item : arrayOrIterable) {
    // Use item
}

The right-hand side must be either an array (primitive or reference type) or an object whose type implements java.lang.Iterable (such as List, Set, or Queue).

String[] codes = {"A1", "B2"};
for (String code : codes) {
    System.out.print(code + " ");
} // Prints: A1 B2

Common invalid right-hand targets that fail compilation:

  • java.util.Map directly: Map does not extend Iterable. To iterate over a Map, traverse map.keySet(), map.values(), or map.entrySet().
  • String directly: String is not an array or Iterable. Use str.toCharArray() to iterate over characters.
  • Single primitives or null literals: for (int n : 5) fails compilation, and iterating over a null array/collection reference compiles (if typed) but throws a NullPointerException at runtime.

Reassignment vs. Object Mutation and ConcurrentModificationException

On every pass of an enhanced for loop, item receives a copy of the current element (a primitive value or an object reference). Therefore:

  1. Reassigning item never changes the array or collection: item = 99; or item = "new"; only updates the local variable item for that iteration.
  2. Mutating the heap object via item DOES persist: If elements are mutable objects like StringBuilder, calling item.append("!") mutates the shared object on the heap.
  3. Structural changes during iteration: Adding or removing directly from an ArrayList during enhanced-for iteration can cause ConcurrentModificationException. Fail-fast checks are best effort. Use an explicit iterator that supports remove(), or apply removeIf(...) outside the traversal if the list supports removal.
  4. No built-in index: If you need the element's index (i) or need to replace array slots, use a traditional for loop.

Nested Loop Tracing and Choosing the Right Loop

The total number of inner iterations is the sum of the inner counts over the outer passes. Only multiply the counts when every outer pass runs the same number of inner iterations. Track how the inner condition depends on the outer variable:

int sum = 0;
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= i; j++) {
        sum += i * j;
    }
}
System.out.println(sum);

Tracing step by step:

  • When i = 1: j runs 1 -> sum += 1 * 1 (sum = 1)
  • When i = 2: j runs 1, 2 -> sum += 2 * 1 (3), sum += 2 * 2 (7)
  • When i = 3: j runs 1, 2, 3 -> sum += 3 * 1 (10), sum += 3 * 2 (16), sum += 3 * 3 (25)
  • Final output: 25
ConstructWhen to Use ItMinimum IterationsIndex AccessNext Step After Continue
whileStop when an input or state fails a test0Track one explicitlyCondition
do-whileEnter the body before checking a condition, such as a menu prompt1Track one explicitlyCondition
Basic forKeep initialization, condition, and update together0Declare or use an index explicitlyUpdate, then condition
Enhanced forTraverse the elements of an array or iterable0Track one separately if neededAdvance traversal

Important

Assigning to the enhanced-for variable does not write to the array. To double each element in place, use an explicit index and assign to array[i].

Test Your Knowledge

What is the output of the following Java code?

int a = 0;
for (a = 1, System.out.print("S"); a < 3; a++, System.out.print("U")) {
    System.out.print(a);
}
A

S12U

B

S1U2U

C

1U2U

D

Compilation fails because System.out.print cannot appear in a for header

Test Your Knowledge

What does the following code snippet print?

StringBuilder[] items = {
    new StringBuilder("A"),
    new StringBuilder("B")
};
for (StringBuilder sb : items) {
    sb.append("1");
    sb = new StringBuilder("X");
}
System.out.println(items[0] + " " + items[1]);
A

X X

B

A B

C

A1 X

D

A1 B1

Test Your Knowledge

Which statement correctly describes iterating over a java.util.Map<String, Integer> named scores using an enhanced for loop?

A

for (Map.Entry<String, Integer> entry : scores.entrySet()) { } compiles, whereas for (String key : scores) { } fails compilation

B

for (String key : scores) { } compiles and iterates over the map’s keys in insertion order

C

for (Integer val : scores) { } compiles and iterates over the map’s values

D

Removing an entry directly from a map during enhanced-for traversal is guaranteed safe for every map implementation

Sections you finish are checked off in the contents.