Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Keywords and Statements

The enhanced for (for-each) statement

Reference for the Java for-each loop: iterating arrays, Lists, Sets and Maps, the Iterable requirement, ConcurrentModificationException and pitfalls.

The enhanced for statement, usually called the for-each loop, visits every element of an array or of any object that implements Iterable. You get each element in a variable and no index to manage, which removes a whole class of off-by-one mistakes.

For arrays the compiler generates an index loop. For an Iterable it calls iterator() and then hasNext() and next(). Because of this, the loop variable is a copy of the element reference, and changing the collection during iteration is restricted.

Java
for (String name : names) {
    System.out.println(name);
}

Try it

Java Arrays, lists and maps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java What the loop variable can and cannot do

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
for (Type variable : arrayOrIterable) {
    body
}
Part Description
Type variable Declared in the header. Can be final, can be var. The element type must be assignable to Type (unboxing and widening apply).
arrayOrIterable An array, or an object whose type implements java.lang.Iterable<T>.

Usage notes

  • No index. If you need the position, use the classic for loop, or keep a separate counter.
  • Assignments to the variable are local. The loop variable is a fresh variable per iteration; assigning to it does not modify the array or collection. Calling mutating methods on the element object does.
  • Fail-fast iterators: adding or removing elements of an ArrayList, HashMap and similar collections while iterating throws ConcurrentModificationException (on a best-effort basis). Use Iterator.remove(), removeIf(), or iterate over a copy. Concurrent collections have weakly consistent iterators instead.
  • null: a null array or Iterable throws NullPointerException. Collections that contain null elements pass them to the variable, so unboxing a null into an int fails.
  • Maps are not Iterable. Loop over entrySet(), keySet() or values(). HashMap order is unspecified; use TreeMap or LinkedHashMap for predictable order.
  • Arrays of arrays: nest two loops; the outer variable has type int[].
  • Primitive streams and forEach are alternatives, but the for-each loop allows break, continue, return and checked exceptions.
  • Custom types become loopable by implementing Iterable<T>.