Menu

Java for-each Loop: Syntax, Examples, and Gotchas

The Java for-each (enhanced for) loop explained - clean iteration over arrays and collections, when to use it, and the modification gotcha that trips everyone up.

This page includes runnable editors - edit, run, and see output instantly.

When the Index Just Gets in the Way

A counted for loop gives you a counter, a condition, and an update step. But a huge amount of the time you do not actually care about the position of an element - you just want to do something with each one, in order, from start to finish. Managing an index for that is busywork, and it is exactly where off-by-one bugs sneak in.

The for-each loop (Java's name for it is the enhanced for) drops the counter entirely. You name a variable, point it at a collection, and the loop hands you each element in turn.

Basic Syntax

The shape is for (Type element : collection). Read the colon as the word "in":

There is no i, no scores.length, no scores[i]. On each pass, score is the next element. The loop runs once per element and stops automatically when there are no more - you cannot run past the end or start one element too early.

Looping Over a List

The same loop works on anything iterable, which includes List, Set, and the other collection types. The element type goes before the variable name:

Notice you did not have to know or care whether langs is backed by an array, a linked list, or anything else - for-each works the same on all of them. That is its real strength: one readable syntax for every collection.

var Saves You the Type Name

If the element type is long or obvious, var lets the compiler infer it so you do not repeat yourself:

Without var, that loop variable would be the mouthful Map.Entry<String, Integer>. var keeps it readable, and the type is still fully checked at compile time - this is not a loose, dynamic type.

The Modification Gotcha

Here is the rule that catches everyone: you cannot add to or remove from a collection while a for-each loop is walking it. Doing so throws a ConcurrentModificationException:

List<String> items = new ArrayList<>(List.of("a", "b", "c"));

for (String item : items) {
    if (item.equals("b")) {
        items.remove(item);   // throws ConcurrentModificationException
    }
}

The loop notices the list changed underneath it and bails out rather than silently skipping or repeating elements. To remove safely, drop down to an explicit Iterator, which has a remove() the loop knows about:

A common shortcut is items.removeIf(item -> item.equals("b")), which uses a lambda expression to do the same thing in one line.

Reading Only, Not Reassigning

Another subtle limit: assigning to the loop variable changes only the local copy, not the collection. This surprises people coming from languages where the loop variable is a live reference:

If you need to write back into the array, you need the index - and that means the classic counted for loop: for (int i = 0; i < nums.length; i++) nums[i] = nums[i] * 10;. For object elements, you can mutate the object the variable points to (calling a setter, say), but you cannot replace it in the collection.

break and continue Still Work

A for-each is a real loop, so break and continue behave exactly as they do elsewhere - break leaves the loop, continue skips to the next element:

This prints keep then keep - it skips "skip" and halts at "stop" before reaching "never". So you are not locked into visiting every element; you just give up the index in exchange for cleaner code.

Next: Arrays

You have now looped over arrays a few times without dwelling on what they actually are - fixed-size, indexed containers with that .length field. The next page goes back to the start and covers arrays properly: declaring them, the default values they start with, and how their fixed size differs from a growable ArrayList.

Frequently Asked Questions

What is a for-each loop in Java?

A for-each loop (also called the enhanced for) walks every element of an array or collection without a counter: for (Type item : collection) { ... }. Read it as "for each item in collection". It is cleaner than a counted for loop when you just need each element and never the index.

What is the difference between a for loop and a for-each loop in Java?

The classic for loop uses an explicit counter (for (int i = 0; i < arr.length; i++)), so you control the index and direction. The for-each loop, for (Type x : arr), has no index - it visits every element in order. Use for-each for read-only, front-to-back passes; use the counted loop when you need the index, want to skip elements, or modify the collection's structure.

Why does my for-each loop throw ConcurrentModificationException?

Because you called add() or remove() on the collection while iterating it with a for-each. The loop detects the structural change and throws to protect you from undefined behavior. To remove elements safely, use an explicit Iterator and its remove() method, or collect the items to delete and remove them after the loop.

Coddy programming languages illustration

Learn to code with Coddy

GET STARTED