Enhanced for-each Loop in Java
Fast recall
Quick revision
Core answer
for loop iterates over an array or an Iterable without exposing an index: for (String item : items). Use it when each element is enough. Use an index loop when you need positions or want to replace array/list slots, and use an Iterator or collection method when removing elements safely.Whether the candidate writes idiomatic modern Java versus using C-style for loops for everything
Using for-each when you need the index, or trying to modify the array through the loop variable, which doesn't work
Explain that for-each calls iterator() behind the scenes for collections, and that you can't remove elements during iteration without Iterator.remove or removeIf
Interview-ready guide
Interview answer
for-each is my default for reading a collection, and the reason is concrete: it deletes the index bookkeeping where almost every off-by-one bug lives. I just say for each order in orders and do the work — no counter, no length check, nothing to get wrong at the boundary. Under the hood it isn't magic. For collections the compiler turns it into an Iterator, calling hasNext and next; for arrays it's plain index access.
That detail explains the classic trap. If you remove from a list while a for-each is walking it, the iterator sees the structure change underneath it and throws ConcurrentModificationException. So when I actually need to delete during traversal, I use removeIf or an explicit Iterator's remove method. The only two times I drop back to a traditional for loop are when I need the index position, or when I'm writing values back into an array — for-each hands you a copy of each element, not a slot you can assign to. For everything else, which is most of the time, for-each is the cleaner, safer choice.
Enhanced for-each Loop in Java
Direct Answer
The enhanced for loop iterates over an array or an Iterable without exposing an index: for (String item : items). Use it when each element is enough. Use an index loop when you need positions or want to replace array/list slots, and use an Iterator or collection method when removing elements safely.
Code Example
For-each handles the two everyday jobs cleanly: walking a collection and summing an array. The moment you need the position number, though, you switch back to a counted loop.
import java.util.*;
public class ForEachExample {
public static void main(String[] args) {
var products = List.of("Laptop", "Mouse", "Keyboard");
// for-each: clean when the index isn't needed
for (String product : products) {
System.out.println("Processing: " + product);
}
// works with arrays too
int[] scores = {85, 90, 78, 92};
int total = 0;
for (int score : scores) total += score;
System.out.println("Sum: " + total);
// when you need the index, use a traditional for
for (int i = 0; i < products.size(); i++) {
System.out.println("Index " + i + " = " + products.get(i));
}
}
}
The last loop is the tell: the only reason it falls back to i is that it prints the position. If you ever find yourself maintaining a separate counter inside a for-each, that's a sign you wanted a traditional for in the first place.
Common Mistakes & Pitfalls
- Adding or removing during iteration — calling
list.remove(x)inside a for-each throwsConcurrentModificationExceptionat runtime and aborts your loop mid-pass; useremoveIf()or an explicitIterator.remove()instead. - Expecting the loop variable to write back —
for (String s : list) { s = "new"; }silently does nothing, becausesis a copy of the reference; you change the local, the list keeps its old values, and you ship a no-op. - Reaching for for-each when you need the index — bolting on a manual counter to print "item 3 of 10" reintroduces exactly the off-by-one risk for-each removed; use a traditional
forwhen position matters. - For-each over a possibly-null collection —
for (var x : maybeNull)throwsNullPointerException, since for-each callsiterator()on the reference; guard nulls before the loop.
Check your understanding
Answer these without looking back at the article.
- Can you modify a collection while using a for-each loop?
- What interface must a class implement to work with a for-each loop?
- What is the difference between for-each and Iterator?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.