Enhanced for Loop (for-each) in Java
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.
The syntax
for (Type element : collection) reads as "for each element of this type in this collection."
No index needed
element receives each value directly, in order, without ever tracking a separate counter.
Works on arrays and Collections
Anything that implements Iterable, which includes every standard collection type, can be used after the colon.
Automatic termination
The loop stops by itself once every element has been visited, with no explicit condition to write or maintain.
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.
public class ForEachDemo { public static void main(String[] args) { String[] fruits = {"apple", "banana", "cherry"}; for (String fruit : fruits) { System.out.println("Fruit: " + fruit); } }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.