Basics

6. The Enhanced For Loop

The enhanced for loop iterates over any Iterable or array cleanly, but it cannot provide an index, cannot remove elements safely, and iterates a copy of the loop variable.

Java 21 (core language)

Explanation

The enhanced for loop (for (Type x : collection)) is syntactic sugar over Iterator. For arrays, the compiler generates a standard indexed loop; for Iterable implementations, it calls iterator() and loops with hasNext()/next().

Key limitations: you cannot remove elements during iteration using the loop variable โ€” call iterator.remove() via an explicit Iterator, or use collection.removeIf(predicate) (Java 8+). You also do not get the index automatically; if you need both the value and the index, use a classic for (int i = 0; ...) loop.

Mutating the loop variable (x = something) only changes the local copy, not the original element in the collection โ€” a common beginner mistake with primitives. For objects, you can still mutate the object's state via its methods, but reassigning x does nothing to the collection.

Example

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class EnhancedForLoop {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of("Alice", "Bob", "Charlie"));

        // Basic enhanced for
        for (String name : names) {
            System.out.println(name);
        }

        // WRONG: ConcurrentModificationException
        // for (String name : names) {
        //     if (name.startsWith("B")) names.remove(name); // throws!
        // }

        // CORRECT: removeIf (Java 8+)
        names.removeIf(n -> n.startsWith("B"));
        System.out.println("After removeIf: " + names); // [Alice, Charlie]

        // CORRECT: explicit Iterator for remove
        List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4, 5));
        Iterator<Integer> it = nums.iterator();
        while (it.hasNext()) {
            if (it.next() % 2 == 0) it.remove();
        }
        System.out.println("Odds only: " + nums); // [1, 3, 5]

        // Need index? Use classic for
        String[] arr = {"a", "b", "c"};
        for (int i = 0; i < arr.length; i++) {
            System.out.println(i + ": " + arr[i]);
        }
    }
}

Sources