What is the enhanced for-each loop in Java and what is its syntax?
answer
- for (Type e : source) — colon reads as 'in'
- Java 5 (2004)
- Works on arrays + Iterable
- No index, no reverse, no safe remove
- Clearest forward read-only traversal
basics
~10 sIt 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 sThe 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
Can write the syntax correctly and explain it visits every element of an array or list without a counter.
Knows it requires array or Iterable, that there's no index, and when to fall back to a classic loop.
Articulates the trade-offs (no index/reverse/step/remove) and picks the construct deliberately for readability and safety.
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