JavaEnhanced for Loop

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

Java
for (Type item : collection) {
    // use item
}

Read it as: "for each item of type Type in collection".

Example: Iterating an Array

Java
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

Java
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

Java
for (int i = 0; i < scores.length; i++) {
    System.out.println(scores[i]);
}

Same logic, enhanced for

Java
for (int score : scores) {
    System.out.println(score);
}
Tip
If you don't need the index itself — only the value at each position — reach for the enhanced for loop by default. Fall back to a classic for loop only when you genuinely need the index (for example, to compare neighboring elements or to modify the array by position).
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

Java
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
Warning
You cannot add or remove elements from the underlying collection during an enhanced for loop over it — this throws a ConcurrentModificationException at runtime. This is one of the most commonly hit surprises for developers new to Java collections.
The Fix: Use an Iterator (or a Classic for Loop)

Fixed: removing safely with an Iterator

Java
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

Java
for (int i = fruits.size() - 1; i >= 0; i--) {
    if (fruits.get(i).equals("banana")) {
        fruits.remove(i);
    }
}
Note
Iterating backward means each removal only affects indices you've already passed, so nothing gets skipped. Going forward while removing by index is a classic source of subtle bugs, even without an exception being thrown.
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
  1. Use an enhanced for loop to sum all elements of an int array.

  2. Use an enhanced for loop to print every uppercase-transformed string in a List<String>.

  3. Deliberately trigger a ConcurrentModificationException by removing from a list during an enhanced for loop, then fix it using an Iterator.