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
// blueRead 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: 345When 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.