W3docs

Java for-each (Enhanced for) Loop

Iterate over arrays and collections in Java with the enhanced for-each loop for simpler, safer iteration.

Java 5 introduced the enhanced for loop — usually called the for-each loop — for walking through every element of an array or collection without managing an index by hand. When you don't need the index, it's almost always the cleanest choice.

Syntax

for (Type element : iterable) {
  // body — runs once per element
}

Read it as: for each element in iterable. The colon is mandatory; it's not the same as the regular for loop's semicolons.

int[] nums = {10, 20, 30, 40};

for (int n : nums) {
  System.out.println(n);
}

Prints 10 20 30 40. No counter, no nums.length, no nums[i].

Works on arrays and any Iterable

The for-each loop accepts:

  • Any array.
  • Anything that implements java.lang.Iterable<T> — which means every Collection (such as List, Set, and Queue), plus many other JDK and library types.
import java.util.List;

List<String> names = List.of("alice", "bob", "carol");
for (String name : names) {
  System.out.println(name);
}

String text = "abc";
for (char c : text.toCharArray()) {
  System.out.println(c);
}

Note that String itself is not iterable, but text.toCharArray() produces an array, which is.

A Map is also not Iterable directly — you iterate one of its views instead: map.keySet(), map.values(), or map.entrySet(). Each of those returns a Set or Collection, which the for-each loop handles.

The element variable is a copy

The variable in the loop header receives the value of each element. For primitives, modifying it doesn't change the array:

int[] nums = {1, 2, 3};
for (int n : nums) {
  n *= 10;          // doesn't touch nums
}
System.out.println(nums[0]);   // still 1

For objects, the variable holds a reference, so calling methods that mutate the object will affect the original. But reassigning the variable (name = "...";) only changes the local copy.

If you need to modify the elements themselves, use an indexed loop:

for (int i = 0; i < nums.length; i++) {
  nums[i] *= 10;
}

When you can't use for-each

A for-each loop hides the index. That's the point — but it also means you can't use one when you need:

  • The index ("item " + i + ": " + value)
  • To remove elements while iterating (use an explicit Iterator and call iterator.remove())
  • Two collections in lockstep (use indices)
  • To iterate in reverse or skip elements (use an indexed for)

Don't modify the collection while iterating

A for-each loop over a collection uses an Iterator internally. If you change the collection's structure during iteration (add or remove elements), the iterator notices the mismatch on the next step and throws a ConcurrentModificationException:

List<String> names = new ArrayList<>(List.of("alice", "bob"));
for (String n : names) {
  names.remove(n);   // ConcurrentModificationException
}

To remove safely, drive the loop with an explicit Iterator and call its remove() — it keeps the iterator and the list in sync:

Iterator<String> it = names.iterator();
while (it.hasNext()) {
  String n = it.next();
  if (n.startsWith("a")) {
    it.remove();      // safe
  }
}

On Java 8+ you can often skip the loop entirely: names.removeIf(n -> n.startsWith("a"));.

Warning

Reading or replacing an element (list.set(i, x)) during a for-each loop is fine. It's only structural changes — add and remove on the collection itself — that trigger the exception.

A worked example

java— editable, runs on the server

What's next

When you need to exit a loop early — or skip the rest of the current iteration — use break and continue.

Practice

Practice
In a for-each loop over an int[], modifying the loop variable inside the body...
In a for-each loop over an int[], modifying the loop variable inside the body...
Was this page helpful?