For Loops in Java
Master Java for loops: traditional for loops, enhanced for-each syntax, when to use each variant, and common iteration patterns with performance considerations.
Master Java for loops: traditional for loops, enhanced for-each syntax, when to use each variant, and common iteration patterns with performance considerations.
For Loops in Java
This guide compares Java’s for forms and shows when to use an explicit iterator to remove an item during traversal.
Introduction
Java’s traditional for loop gives direct control over an index, condition, and update. The enhanced for-each loop, added in Java 5, is shorter when you only need each value. For arrays, it uses index-based traversal; for an Iterable, it uses an iterator, as described in JLS SE 27 §14.14.2.
Enhanced for-each does not expose the iterator it uses, so it cannot call that iterator’s remove() method for you. If you need to remove items while traversing a collection, hold an Iterator and call remove() when supported. Structural changes made elsewhere during iteration may trigger ConcurrentModificationException on fail-fast collections such as ArrayList; that check is best-effort, not a correctness guarantee. See the Java SE 27 Iterator API and ArrayList API.
The examples cover index-based loops, enhanced traversal, nested loops, and supported iterator removal, along with common errors such as off-by-one bounds and null collections.
When to Use / Not to Use
Use traditional for loop when:
- You need the loop variable for indexing or calculations
- You need precise control over iteration (step size, custom termination)
- Traversing multiple arrays in parallel (i.e., with index)
- Reversing iteration is required
Use enhanced for-each when:
- Traversing arrays or collections without needing the index
- Read-only traversal of elements
- Simple iteration where you do not need index or iterator operations
Do not use for loops when:
- Iterating based on a predicate (consider while or stream)
- You need iterator operations such as removal (use an explicit iterator when its
remove()operation is supported) - You need to modify a collection from somewhere else while its iterator is active; fail-fast behavior may detect this, but it is best-effort
Diagram: Traditional vs Enhanced For Loop
flowchart TD
A["Traditional: for (init; condition; update)"] --> B["Initialize"]
B --> C{"Condition true?"}
C -->|yes| D["Execute body"]
D --> E["Update"]
E --> C
C -->|no| F["Exit loop"]
G["Enhanced: for (element : collection)"] --> H["Get next element"]
H --> I{"Has element?"}
I -->|yes| J["Execute with element"]
J --> H
I -->|no| K["Exit loop"]
Code Snippet: Loop Patterns
import java.util.Arrays;
import java.util.List;
public class ForLoopDemo {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
String[] names = {"Alice", "Bob", "Charlie"};
List<String> fruits = Arrays.asList("Apple", "Banana", "Cherry");
// Traditional for loop with index
System.out.println("Traditional loop:");
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element " + i + ": " + numbers[i]);
}
// Traditional with multiple variables
System.out.println("\nParallel arrays:");
for (int i = 0; i < names.length; i++) {
System.out.println(names[i] + " -> " + numbers[i]);
}
// Enhanced for-each loop
System.out.println("\nEnhanced for-each:");
for (int num : numbers) {
System.out.println("Value: " + num);
}
// For-each with collections
System.out.println("\nFor-each collection:");
for (String fruit : fruits) {
System.out.println("Fruit: " + fruit);
}
// Nested loops
System.out.println("\nNested loop (matrix):");
int[][] matrix = {{1, 2}, {3, 4}, {5, 6}};
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
// Enhanced for nested (for 2D arrays)
System.out.println("\nEnhanced nested (for 2D):");
for (int[] row : matrix) {
for (int cell : row) {
System.out.print(cell + " ");
}
System.out.println();
}
// Reverse iteration (traditional only)
System.out.println("\nReverse iteration:");
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.println(numbers[i]);
}
// Step by 2
System.out.println("\nEven indices:");
for (int i = 0; i < numbers.length; i += 2) {
System.out.println(numbers[i]);
}
}
}
Exercise: Array, List, and Iterator Traversal
This short program shows array traversal, indexed access to a List, read-only enhanced for-each, and removal through an explicit iterator. ArrayList supports Iterator.remove().
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class ForLoopTraversalExercise {
public static void main(String[] args) {
int[] numbers = {2, 4, 6};
System.out.print("Array: ");
for (int i = 0; i < numbers.length; i++) {
if (i > 0) {
System.out.print(" ");
}
System.out.print(numbers[i]);
}
System.out.println();
List<String> colors = new ArrayList<>(Arrays.asList("red", "blue", "red", "green"));
System.out.println("Indexed list:");
for (int i = 0; i < colors.size(); i++) {
System.out.println(i + " = " + colors.get(i));
}
System.out.println("Enhanced for-each:");
for (String color : colors) {
System.out.println(color);
}
Iterator<String> iterator = colors.iterator();
while (iterator.hasNext()) {
if (iterator.next().equals("red")) {
iterator.remove();
}
}
System.out.println("After iterator removal: " + colors);
}
}
Expected output:
Array: 2 4 6
Indexed list:
0 = red
1 = blue
2 = red
3 = green
Enhanced for-each:
red
blue
red
green
After iterator removal: [blue, green]
Failure Scenarios
| Scenario | Problem | Solution |
|---|---|---|
| Off-by-one errors | Loop runs one time too few or too many | Use inclusive/exclusive bounds carefully |
| Structural modification outside the active iterator | A fail-fast iterator may throw ConcurrentModificationException |
Use the iterator’s supported remove() operation, or change the collection before/after traversal |
| Infinite loop | Condition never becomes false | Ensure update statement changes condition |
| Empty collection | Loop doesn’t execute | Use guard clause if empty handling needed |
Trade-off Table
| Loop Type | Use When | Readability | Performance |
|---|---|---|---|
| Traditional | Need index, step, or reverse | Good for complex | Slightly faster for arrays |
| Enhanced for-each | No index needed | Best for simple traversal | Same (compiler optimizes) |
| Nested loops | Multi-dimensional traversal | Good | Optimize outer-to-inner |
Observability Checklist
- Log loop bounds in debug mode for troubleshooting
- Instrument iteration count metrics for performance monitoring
- Add assertions for loop invariants (e.g., index in bounds)
- Monitor for infinite loops in production (timeout mechanisms)
- Test empty and single-element collection handling
Security Notes
- Resource exhaustion: Infinite or very large loops can cause DoS; implement timeouts or iteration limits
- Array bounds: Ensure loop bounds match actual array size; off-by-one can cause ArrayIndexOutOfBoundsException
- Iterator invalidation: External structural changes can make traversal unsafe; fail-fast checks are best-effort and do not replace correct synchronization or iterator use
Pitfalls
- Removing items in enhanced for-each: The loop hides the iterator, so it cannot call
Iterator.remove(). Use an explicit iterator if its optionalremove()operation is supported. Structural changes made outside the active iterator may trigger a best-effortConcurrentModificationExceptionon fail-fast collections. - Off-by-one in termination:
i <= array.lengthreads one past the end. Usei < array.length. - Loop variable scope: The loop variable is not in scope outside the loop in pre-Java 12 (use a separate variable if needed after).
- Side effects in condition/update: Can cause unexpected behavior; keep loop control clear.
- Enhanced for on null: Throws NullPointerException if collection is null
Quick Recap
- Traditional for:
for (init; condition; update)gives full control over iteration - Enhanced for-each:
for (element : collection)for traversal when you do not need the index or iterator operations - Use traditional when you need the index or custom iteration
- Use enhanced for simple element access without index
- To remove while traversing, use an explicit iterator and its supported
remove()method - Fail-fast collections may throw
ConcurrentModificationExceptionafter external structural changes, but the check is best-effort
Interview Questions
Traditional for: for (int i = 0; i < n; i++) gives you control over the loop variable, step size, and termination. Enhanced for-each: for (element : collection) is cleaner but hides the iterator or array index. Use traditional when you need the index; use enhanced for-each for simple traversal.
For an Iterable, enhanced for-each uses an iterator internally but does not expose it. A structural change made elsewhere may cause a fail-fast iterator such as ArrayList's to throw ConcurrentModificationException. This check is best-effort and must not be used for correctness. To remove the last element returned during traversal, call Iterator.remove() if that implementation supports it; otherwise it may throw UnsupportedOperationException.
Use the traditional for loop with reverse bounds: for (int i = array.length - 1; i >= 0; i--). The enhanced for-each cannot iterate in reverse. Alternatively, use Collections.reverse() on a list copy if you need reverse order.
Enhanced for-each on a null collection throws NullPointerException. Before iterating, either check for null: if (collection != null) { for (item : collection) {...} }, or use Optional.ofNullable(collection).ifPresent(...), or initialize collections to empty collections rather than null.
Prefer while when: (1) the number of iterations is not known upfront, (2) you're iterating until a condition becomes true (like reading until EOF), (3) the termination depends on something that changes inside the loop body. Use for when you know the iteration count or have a classic index-based loop.
In for (i = 0; i < n; i++), both i++ and ++i produce the same final result. The difference matters only if you use the value of the increment expression itself. For loop update is a standalone expression, so the postfix/prefix distinction has no practical effect.
All three parts of a for loop can be empty. for (;;) is an infinite loop, equivalent to while (true). for (;condition;) is a while loop. for (int i = 0; i < n;) is valid but unusual; put the update in the update section for readability.
Off-by-one errors occur when loop bounds are incorrect: i <= array.length reads one past the end. Use i < array.length for zero-based indexing. Always verify the first and last iteration produce the expected values by testing boundary conditions.
The Java language specification translates enhanced for-each over an array into index-based traversal. For an Iterable, it translates the loop to use an iterator. In both cases the source syntax hides those details; only an explicitly obtained iterator exposes operations such as remove().
In Java 12+, the loop variable is scoped to the loop body only and not visible after the loop. In earlier versions, the variable is in scope after the loop. Java 12+ prevents accidental use of the loop variable after the loop, which could be misleading if its final value is unexpected.
Initialization sets up loop variables before the first iteration. The boolean condition is checked before each iteration, and the update expression runs after the body. Each part is optional; for (;;) loops indefinitely.
Yes: for (int i = 0, j = n - 1; i < j; i++, j--) declares multiple variables separated by commas. Both i and j are in scope for the loop. This is useful for parallel iteration (e.g., two-pointer algorithms) and reversing in place.
The update section can have multiple comma-separated expressions: for (int i = 0; i < n; i++, j--) executes both i++ and j-- after each iteration. All expressions are evaluated left-to-right. You can also combine this with multiple initialization variables.
Both create infinite loops. for (;;) shows that initialization, condition, and update are omitted. while (true) makes the condition explicit. Choose the form that reads more clearly in its context.
Yes, the loop body can be empty (a single semicolon). for (int i = 0; i < n; i++); loops n times doing nothing. This is sometimes used for delay loops or when the logic is entirely in the update section. The semicolon is required to mark the empty body.
In Java 12+, a variable declared in the for loop initializer is scoped to the loop only and is not visible after the loop ends. In earlier Java versions, the variable remains in scope after the loop. Java 12+ prevents accidental use of loop variables outside their intended scope.
Enhanced for-each on a null collection throws NullPointerException. Before iterating, check for null: if (collection != null) { for (item : collection) {...} }. Alternatively, use Optional.ofNullable(collection).ifPresent(...) or initialize collections to empty rather than null.
For ArrayList, the compiler generates equivalent code: for-each becomes for (Iterator i = list.iterator(); i.hasNext(); ). For ArrayList with random access, traditional for with index for (int i = 0; i < list.size(); i++) is slightly faster because it avoids iterator allocation, though the JIT often eliminates this difference.
Enhanced for-each visits each element in turn. To skip by position, use a traditional loop with a step, such as for (int i = 0; i < n; i += 2). To skip by value, filter the stream before iterating, for example with list.stream().filter(...).forEach(...).
Enhanced for-each does not expose an array index or an Iterator, so it is not the right form when you need reverse indexing, custom steps, parallel traversal, or iterator operations. For collection removal, use an explicit iterator and call its optional remove() method when supported. Structural changes made outside an active fail-fast iterator may throw ConcurrentModificationException, but that behavior is best-effort and not a correctness mechanism.
Further Reading
- While and Do-While Loops - When iteration count is unknown
- Break, Continue, and Labels - Control flow within loops
- Enhanced For-Each and Iterators - Collection traversal patterns
- Stream API - Functional alternatives to explicit iteration
- Java SE 27 JLS SE 27 §14.14.2 - Enhanced
forstatement translation for arrays andIterablevalues - Java SE 27
IteratorAPI - Optionalremove()operation - Java SE 27
ArrayListAPI - Best-effort fail-fast iterator behavior
Conclusion
Use the traditional for loop when you need an index, reverse traversal, or a custom step. Enhanced for-each is concise when you simply need to process each value.
For an Iterable, enhanced for-each uses an iterator internally but does not expose it. If you need to remove elements during traversal, use an explicit iterator and call its remove() method when supported. An external structural change may trigger ConcurrentModificationException on a fail-fast iterator such as ArrayList’s, but fail-fast behavior is best-effort and not a correctness guarantee. All loop forms pair with break, continue, and labeled statements for early exit and iteration skipping.
When you do not know the iteration count in advance, such as when reading until EOF or waiting for external state, consider while and do-while loops.
Category
Related Posts
Abstract Classes in Java: Interfaces and Composition
Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.
Arithmetic Operators in Java: Division, Overflow, Promotion
Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.
Java Array Basics: Length, Bounds, Copies, and Resizing
Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.