Learn Java
import com.learnjava.controlflow.EnhancedForLoop;

Enhanced for Loop (for-each) in Java

@Concept

The enhanced for loop, often called for-each, iterates directly over every element of an array or a Collection without needing an index variable at all: for (String name : names) hands each element to name in turn, from the first to the last, and stops automatically once every element has been visited. It's shorter and less error-prone than a traditional indexed for loop whenever the index itself isn't actually needed for anything.

The trade-off is that for-each can't easily go backwards, skip elements, access the current index, or modify the underlying collection's structure while iterating — any of those needs calls for a traditional for loop or an explicit Iterator instead.

@HowItWorks
1

The syntax

for (Type element : collection) reads as "for each element of this type in this collection."

2

No index needed

element receives each value directly, in order, without ever tracking a separate counter.

3

Works on arrays and Collections

Anything that implements Iterable, which includes every standard collection type, can be used after the colon.

4

Automatic termination

The loop stops by itself once every element has been visited, with no explicit condition to write or maintain.

5

What it can't do

for-each can't count backwards, skip elements, know the current index, or safely add or remove elements from the collection mid-iteration.

@Example
public class ForEachDemo {
public static void main(String[] args) {
String[] fruits = {"apple", "banana", "cherry"};
for (String fruit : fruits) {
System.out.println("Fruit: " + fruit);
}
}
}
Output
Fruit: apple
Fruit: banana
Fruit: cherry
1fruit takes on "apple" first, the array's first element, and the body prints it.
2On the next iteration, fruit becomes "banana", and the body runs again.
3On the final iteration, fruit becomes "cherry", the array's last element.
4Once every element has been visited, the loop ends automatically, having printed exactly three lines.
@UseCases
Reading every element of an array or list when the index itself isn't needed
Writing shorter, less error-prone iteration code than a manually indexed for loop
Summing, searching, or printing every item in a collection
Recognizing when a for-each won't work, like needing to remove elements while iterating

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Java yourself — building beats watching.