The Enhanced for-each Loop
The Enhanced for-each Loop
The regular for loop is powerful, but it comes with boilerplate: you declare a counter, compare it to a length, and increment it — just to visit every element. Java offers a cleaner alternative called the enhanced for loop (also called the for-each loop). It is designed for exactly one job: iterating over every element in an array or collection, without managing an index at all.
Syntax
The syntax is deliberately minimal:
Read the colon : as "in". So for (String name : names) reads as "for each String called name in names". Java handles getting each element and stopping at the end — you do nothing extra.
Iterating an Array
Here is the same task written first with a traditional for loop and then with for-each, so you can see the difference:
Both print:
The for-each version has no index variable, no length comparison, and no [i] subscript. The code says exactly what it means: "for each fruit, print it".
Iterating a List
For-each works with any class that implements Iterable, which includes all standard Java collections such as ArrayList, LinkedList, and HashSet:
Iterating a Set
For-each works the same way with a Set. The difference is that a Set has no guaranteed order, so the elements may print in any sequence:
When for-each Is NOT Appropriate
For-each is excellent for read-only traversal, but it has real limitations. You must use a regular for loop (or another approach) when:
- You need the index. For-each gives you no position information. If you need to print "Element 0 is Apple", you need
i. - You need to modify an array element. Assigning to the loop variable does not change the original array:
for loop with an index if you need to update elements in place.
- You need to iterate two arrays in parallel. For-each works on one collection at a time. If you need to compare or combine two arrays element-by-element, you need an index.
- You need to iterate backwards. For-each always goes forward, from the first element to the last. There is no reverse mode.
- You need to remove elements from a collection while iterating. Removing from a
Listinside a for-each throws aConcurrentModificationException. Use anIteratororremoveIf()instead.
for loop the moment you need an index, reverse traversal, or in-place modification.
For-Each with Multidimensional Arrays
You can nest for-each loops to walk a 2D array. The outer loop gives you each row (which is itself an array), and the inner loop gives you each element in that row:
Output:
Summary
The enhanced for-each loop removes the clutter of index management and makes iteration code easier to read. Use it freely when you want to visit every element of an array or collection in order. Remember its constraints — no index, no in-place mutation of array elements, no reverse iteration — and switch to a regular for loop when any of those limitations apply.