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
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:
initializationexecutes once before the loop starts.booleanConditionis evaluated. Iffalse, the loop terminates immediately without entering the body.bodyexecutes.updateexecutes 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.- Control returns to step 2 (
booleanCondition).
Consider this trace:
for (int i = 0; i < 3; i++) {
System.out.print(i + " ");
}
| Pass | i at Condition | i < 3 | Output | i after Update |
|---|---|---|---|---|
| 1 | 0 | true | 0 | 1 |
| 2 | 1 | true | 1 | 2 |
| 3 | 2 | true | 2 | 3 |
| 4 | 3 | false | (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++) { ... }usesintandint[]with one base type. - Reassigning pre-declared variables in
init: If variables already exist before theforloop, you may reassign them ininiteven if their types differ. - Valid
initandupdatestatements: Both clauses can contain comma-separated expression statements (such as assignments, increments, or method calls likeSystem.out.print(...)). - Single
booleanCondition: You cannot put comma-separated expressions in the condition clause; it must be a single expression of typebooleanorBoolean(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.Mapdirectly:Mapdoes not extendIterable. To iterate over aMap, traversemap.keySet(),map.values(), ormap.entrySet().Stringdirectly:Stringis not an array orIterable. Usestr.toCharArray()to iterate over characters.- Single primitives or
nullliterals:for (int n : 5)fails compilation, and iterating over anullarray/collection reference compiles (if typed) but throws aNullPointerExceptionat 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:
- Reassigning
itemnever changes the array or collection:item = 99;oritem = "new";only updates the local variableitemfor that iteration. - Mutating the heap object via
itemDOES persist: If elements are mutable objects likeStringBuilder, callingitem.append("!")mutates the shared object on the heap. - Structural changes during iteration: Adding or removing directly from an
ArrayListduring enhanced-for iteration can causeConcurrentModificationException. Fail-fast checks are best effort. Use an explicit iterator that supportsremove(), or applyremoveIf(...)outside the traversal if the list supports removal. - No built-in index: If you need the element's index (
i) or need to replace array slots, use a traditionalforloop.
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:jruns1->sum += 1 * 1(sum = 1) - When
i = 2:jruns1, 2->sum += 2 * 1(3),sum += 2 * 2(7) - When
i = 3:jruns1, 2, 3->sum += 3 * 1(10),sum += 3 * 2(16),sum += 3 * 3(25) - Final output:
25
| Construct | When to Use It | Minimum Iterations | Index Access | Next Step After Continue |
|---|---|---|---|---|
while | Stop when an input or state fails a test | 0 | Track one explicitly | Condition |
do-while | Enter the body before checking a condition, such as a menu prompt | 1 | Track one explicitly | Condition |
Basic for | Keep initialization, condition, and update together | 0 | Declare or use an index explicitly | Update, then condition |
Enhanced for | Traverse the elements of an array or iterable | 0 | Track one separately if needed | Advance 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].
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);
}
S12U
S1U2U
1U2U
Compilation fails because System.out.print cannot appear in a for header
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]);
X X
A B
A1 X
A1 B1
Which statement correctly describes iterating over a java.util.Map<String, Integer> named scores using an enhanced for loop?
for (Map.Entry<String, Integer> entry : scores.entrySet()) { } compiles, whereas for (String key : scores) { } fails compilation
for (String key : scores) { } compiles and iterates over the map’s keys in insertion order
for (Integer val : scores) { } compiles and iterates over the map’s values
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.