🌱BeginnerLoops

for-each Loop

Iterate over arrays and collections cleanly with the enhanced for loop (for-each) - no index management required.

Overview

The enhanced for loop (commonly called "for-each") provides a clean way to iterate over every element in an array or collection without managing an index variable. It reads naturally as "for each element in the collection, do something." When you don't need the index and just want to process each element, for-each is more readable and less error-prone than a traditional for loop. It also works with any class that implements the Iterable interface, including ArrayList, HashSet, and more.

Key Points

  • •Syntax: for (Type element : collection) { ... }
  • •The colon : reads as "in" - "for each int n in numbers"
  • •Cannot modify the collection while iterating; cannot use the index to access other positions
  • •Works with arrays, ArrayList, HashSet, and anything implementing Iterable
  • •Use a regular for loop when you need the index, need to skip elements, or iterate backwards
  • •The loop variable is a copy for primitives - modifying it does not change the original array

Examples

Iterating over an array

public class Main {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};

        // Traditional for loop
        for (int i = 0; i < numbers.length; i++) {
            System.out.print(numbers[i] + " ");
        }
        System.out.println();

        // for-each - cleaner when index is not needed
        for (int n : numbers) {
            System.out.print(n + " ");
        }
        System.out.println();
    }
}

Both loops produce the same output. For-each is preferred when the index is not used.

for-each with String array and calculation

public class Main {
    public static void main(String[] args) {
        String[] fruits = {"Apple", "Banana", "Cherry", "Date"};

        for (String fruit : fruits) {
            System.out.println(fruit + " has " + fruit.length() + " letters");
        }

        // Sum elements
        int[] scores = {85, 92, 78, 95, 88};
        int total = 0;
        for (int score : scores) {
            total += score;
        }
        System.out.println("Average: " + (total / scores.length));
    }
}

for-each is ideal for processing each element - summing, searching, printing.

When to use for-each vs regular for

int[] data = {5, 2, 8, 1, 9, 3};

// USE FOR-EACH: you just want each value
for (int val : data) {
    System.out.println(val);
}

// USE REGULAR FOR: you need the index
for (int i = 0; i < data.length; i++) {
    System.out.println("data[" + i + "] = " + data[i]);
}

// USE REGULAR FOR: counting backward
for (int i = data.length - 1; i >= 0; i--) {
    System.out.print(data[i] + " ");
}

For-each cannot go backwards or provide the current index.

Common Mistakes

  • Trying to modify the original array via the loop variable: `for (int n : nums) { n *= 2; }` - n is a copy, the array is unchanged
  • Using for-each when you need the index to modify the element - use a regular for loop instead
  • ConcurrentModificationException: modifying a List while iterating over it with for-each

Note

As a default, reach for for-each when iterating arrays and lists. Switch to a regular indexed for loop only when you explicitly need the index or need to modify elements in place.

Exercises

Write Java code and click Run to execute it instantly. When your output looks correct, mark as done.

Loading editor…

Completed: 0 / 4 exercises

Knowledge Check

Question 1 of 4

What does the colon (:) mean in `for (int n : numbers)`?