Control Flow & Loops

The Enhanced for-each Loop

15 min Lesson 7 of 14

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:

for (Type element : collectionOrArray) { // use element }

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:

String[] fruits = {"Apple", "Banana", "Cherry"}; // Traditional for loop for (int i = 0; i < fruits.length; i++) { System.out.println(fruits[i]); } // Enhanced for-each — same output, less noise for (String fruit : fruits) { System.out.println(fruit); }

Both print:

Apple Banana Cherry

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:

import java.util.List; List<Integer> scores = List.of(85, 92, 78, 95, 60); int total = 0; for (int score : scores) { total += score; } System.out.println("Total: " + total); System.out.println("Average: " + (total / scores.size()));
List.of() creates an immutable list. It is a modern, concise way to create a read-only list from a set of values. You will meet it often in examples throughout this course.

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:

import java.util.Set; Set<String> colors = Set.of("Red", "Green", "Blue"); for (String color : colors) { System.out.println(color); // order is not guaranteed }

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:

  1. You need the index. For-each gives you no position information. If you need to print "Element 0 is Apple", you need i.
  2. You need to modify an array element. Assigning to the loop variable does not change the original array:
int[] numbers = {1, 2, 3}; for (int n : numbers) { n = n * 2; // this only changes the LOCAL copy of n } // numbers is still {1, 2, 3} — nothing changed! System.out.println(numbers[0]); // prints 1
for-each cannot modify array elements. The loop variable is a copy of each value (for primitives) or a copy of the reference (for objects). Reassigning the variable has no effect on the original array or list. Use a traditional for loop with an index if you need to update elements in place.
  1. 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.
  2. You need to iterate backwards. For-each always goes forward, from the first element to the last. There is no reverse mode.
  3. You need to remove elements from a collection while iterating. Removing from a List inside a for-each throws a ConcurrentModificationException. Use an Iterator or removeIf() instead.
Rule of thumb: reach for for-each whenever you only need to read every element in sequence. Switch to a regular 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:

int[][] grid = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; for (int[] row : grid) { for (int value : row) { System.out.print(value + " "); } System.out.println(); }

Output:

1 2 3 4 5 6 7 8 9

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.