Java Enhanced for Loop
What is the Enhanced for Loop?
The enhanced for loop — often called the "for-each" loop — lets you walk through every element of an array or collection without managing an index variable yourself. Instead of asking "give me element number i", you simply say "give me each item", one at a time, in order.
Basic Syntax
for (Type item : collection) {
// use item
}Read it as: "for each item of type Type in collection".
Example: Iterating an Array
int[] scores = {88, 92, 76, 100, 65};
for (int score : scores) {
System.out.println("Score: " + score);
}Score: 88 Score: 92 Score: 76 Score: 100 Score: 65
Example: Iterating a List
List<String> names = List.of("Amina", "Chen", "Diego");
for (String name : names) {
System.out.println("Hello, " + name + "!");
}Hello, Amina! Hello, Chen! Hello, Diego!
Why Prefer Enhanced for?
No manual index variable to declare, increment, or accidentally mistype.
No risk of an off-by-one error — no i < arr.length vs i <= arr.length confusion.
No risk of an ArrayIndexOutOfBoundsException caused by a bad loop bound.
Reads closer to plain English, which makes intent obvious to anyone reading the code.
Classic index loop
for (int i = 0; i < scores.length; i++) {
System.out.println(scores[i]);
}Same logic, enhanced for
for (int score : scores) {
System.out.println(score);
}The Big Gotcha: Modifying a Collection While Iterating
The enhanced for loop iterates using the collection's internal iterator. If you add or remove elements from the collection WHILE that loop is running, the iterator notices its structure changed underneath it and throws a ConcurrentModificationException — even though you're not using threads at all.
Broken: removing during an enhanced for loop
List<String> fruits = new ArrayList<>(List.of("apple", "banana", "cherry"));
for (String fruit : fruits) {
if (fruit.equals("banana")) {
fruits.remove(fruit); // throws ConcurrentModificationException
}
}Exception in thread "main" java.util.ConcurrentModificationException
The Fix: Use an Iterator (or a Classic for Loop)
Fixed: removing safely with an Iterator
List<String> fruits = new ArrayList<>(List.of("apple", "banana", "cherry"));
Iterator<String> it = fruits.iterator();
while (it.hasNext()) {
String fruit = it.next();
if (fruit.equals("banana")) {
it.remove(); // safe: the iterator itself performs the removal
}
}
System.out.println(fruits);[apple, cherry]
Alternatively, if you're working with an array-backed list and removing by index, a classic for loop iterating backward avoids skipping elements after a removal shifts everything down:
Fixed: classic for loop, iterating backward
for (int i = fruits.size() - 1; i >= 0; i--) {
if (fruits.get(i).equals("banana")) {
fruits.remove(i);
}
}Enhanced for vs Classic for
Aspect | Enhanced for | Classic for |
Access to index | No | Yes |
Risk of off-by-one errors | None | Possible |
Can modify collection structure while looping | No — throws ConcurrentModificationException | Careful use is possible |
Readability for simple traversal | Excellent | More verbose |
Practice Exercises
Use an enhanced for loop to sum all elements of an int array.
Use an enhanced for loop to print every uppercase-transformed string in a List<String>.
Deliberately trigger a ConcurrentModificationException by removing from a list during an enhanced for loop, then fix it using an Iterator.