skip to content

Enhanced for-each Loop

The enhanced for loop desugars to index iteration over arrays and to an Iterator over anything Iterable. Knowing that it uses the iterator is what explains ConcurrentModificationException when you remove inside the loop.

part ofJavaoverview, primer and where to startread it →
on this pageshow

questions

5

What is the enhanced for-each loop in Java and what is its syntax?

level: juniorimportance: must knowfreq 70%

answer

  1. for (Type e : source) — colon reads as 'in'
  2. Java 5 (2004)
  3. Works on arrays + Iterable
  4. No index, no reverse, no safe remove
  5. Clearest forward read-only traversal

basics

~10 s

It is a shorter loop for going through every element of an array or collection without a counter. You write 'for (Type item : collection)' and 'item' takes each value in turn.

solid answer

~40 s

The enhanced for-each loop, added in Java 5, iterates over every element of an array or any object implementing Iterable, exposing each element in a loop variable. Syntax: for (ElementType e : source) { ... }. You read it as 'for each e in source'. It removes the manual index or iterator bookkeeping you'd write in a classic for loop, so there is no off-by-one risk and the intent (visit every element) is explicit. Its trade-off is reduced control: you have no index, you can't easily iterate backwards or skip by step, and you cannot safely remove elements from the collection during iteration. It is the idiomatic choice for straightforward read-only traversal.

go deeper

for a junior

Can write the syntax correctly and explain it visits every element of an array or list without a counter.

for a middle

Knows it requires array or Iterable, that there's no index, and when to fall back to a classic loop.

for a senior

Articulates the trade-offs (no index/reverse/step/remove) and picks the construct deliberately for readability and safety.

for a principal

Frames for-each as part of guiding a team toward intent-revealing, low-defect code, and knows the desugaring (iterator vs index) that drives correctness and performance characteristics.

## What it is The **enhanced for-each loop** (often just 'for-each', sometimes 'foreach') is a Java language construct, introduced in **Java 5 (2004)**, for iterating over a sequence of elements without writing explicit index arithmetic or iterator calls. A **loop** is code that repeats; **iterating** means visiting each element of a group one at a time. ## Syntax ```java for (ElementType element : source) { // body runs once per element } ``` Read the colon as the word **'in'**: 'for each element in source'. `source` must be either an **array** (a fixed-size block of same-typed values) or an object whose class implements the **`Iterable`** interface (an interface is a contract a class promises to fulfill; `Iterable` means 'I can be looped over'). Most collection types — `List`, `Set`, etc. — implement `Iterable`. ## Compared to the classic for loop The traditional loop needs three parts you maintain by hand: ```java for (int i = 0; i < names.length; i++) { String name = names[i]; } ``` Here `i` is an **index** (a counter / position number), `i < names.length` is the stop condition, and `i++` advances it. Getting any of these wrong causes an **off-by-one error** (visiting one too few or one too many elements) or an `IndexOutOfBoundsException`. The for-each form hides all three: ```java for (String name : names) { // name is already the value } ``` ## What you give up - **No index**: you don't know the element's position number inside the loop. - **No reverse / step iteration**: you always go front to back, one at a time. - **No safe removal**: removing from the underlying collection during the loop throws `ConcurrentModificationException`. - **Single source**: you can't advance two collections in lockstep in one header. ## Term glossary - **Array**: fixed-length sequence of values of one type, e.g. `int[]`. - **Iterable**: interface with one method, `iterator()`, returning an `Iterator`. - **Iterator**: object with `hasNext()` and `next()` used to walk a collection. ## When to use it Use for-each for plain, forward, read-only traversal — it is the clearest and least error-prone option. Drop to a classic for loop or an explicit iterator only when you need the index, reverse order, a step other than 1, or in-loop removal.

  • Can you get the current index inside a for-each loop?
    Not directly. The header exposes only the element. If you need the position you must maintain a separate counter yourself, or switch to a classic indexed for loop.
  • What types can appear after the colon?
    An array of any type, or any object whose class implements java.lang.Iterable (which all the standard collections do).

saying these in an interview costs you the question

  • Thinking for-each gives you an index variable
  • Believing it works on Map directly (you iterate map.entrySet()/keySet()/values(), not the Map itself)
  • Assuming you can iterate in reverse with for-each

context

open as a page

What happens if you remove or add elements to a collection while iterating it with a for-each loop, and how do you remove safely?

level: middleimportance: must knowfreq 75%

basics

~10 s

Changing the collection's size during a for-each usually throws a ConcurrentModificationException. To remove items safely, use an explicit Iterator and call its remove(), or use collection.removeIf(...).

open as a page

How does the for-each loop iterate over an array versus an Iterable, and what does the compiler generate for each?

level: middleimportance: should knowfreq 55%

basics

~10 s

For an array the compiler turns it into an index-based loop using array.length. For a collection it calls iterator() and uses hasNext()/next(). The source code looks the same, but the generated code differs.

open as a page

How would you make your own class usable in a for-each loop?

level: seniorimportance: should knowfreq 40%

basics

~10 s

Make the class implement Iterable<T> and provide an iterator() method that returns an Iterator<T> with working hasNext() and next() methods. Then it can be used directly in for-each.

open as a page

When should you NOT use a for-each loop, and what should you use instead?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Avoid for-each when you need the index, want to go in reverse or skip elements, must remove items, or must walk two collections together. Use a classic indexed for loop, an explicit Iterator, or removeIf instead.

open as a page