Java For Each Loop

The for-each loop, also called the enhanced for loop, gives you a clean way to visit every element in an array or collection without managing an index yourself. When you just need each item in turn, it is often the easiest and safest option.

A simpler way to loop

Instead of writing a counter, a condition, and an update, you declare one variable that receives each element in order. Java handles the walking for you, so there is no chance of an off-by-one mistake or going past the end of the array.

For-each over an array

String[] colors = {"red", "green", "blue"};

for (String color : colors) {
  System.out.println(color);
}

// Output:
// red
// green
// blue

Read the colon as the word "in". The loop above says "for each color in colors", which is close to plain English and makes the intent obvious.

Working with numbers

The for-each loop works with any array type. Here we add up an array of integers to find their total without ever touching an index.

Summing values with for-each

int[] scores = {90, 85, 100, 70};
int total = 0;

for (int score : scores) {
  total += score;
}

System.out.println("Total: " + total);
// Output: Total: 345
Note: The for-each variable is a copy of each element. Reassigning it inside the loop does not change the original array, so use a classic for loop when you need to modify elements in place.

When to choose which loop

  • Use for-each when you only need to read each element in order.
  • Use a classic for loop when you need the index number.
  • Use a classic for loop when you must change elements or skip around.
  • For-each cannot easily loop backward or over part of an array.
You need to...Best loop
Read every item oncefor-each
Know the position of each itemclassic for
Modify array contentsclassic for
Loop in reverseclassic for
Note: Prefer the for-each loop for simple read-through tasks. It has less to type, reads more clearly, and removes a whole class of indexing bugs.