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 (List, Set, 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.

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 modify the collection's structure during iteration (add or remove from it), you'll get a ConcurrentModificationException:

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

Use Iterator.remove() or filter into a new list instead.

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...