Java for-each Loop

The for-each loop (also known as the enhanced for loop) in Java provides a simpler and cleaner way to iterate through elements of arrays or collections such as ArrayList, HashSet, etc. Introduced in Java 5, this loop eliminates the need for a counter variable or iterator object when traversing through a sequence of elements.

Syntax of the for-each Loop

for (datatype variable : collection_or_array) {
  // Code to be executed for each element
}

Explanation:

datatype → The type of elements contained in the collection or array.

variable → A temporary variable that stores each element during iteration.

collection_or_array → The array or collection that you want to iterate through.

Example 1: Using for-each Loop with an Array

Let’s start with a simple example that prints all elements of an array.

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

    System.out.println(“Array elements:”);
    for (int num : numbers) {
      System.out.println(num);
    }
  }
}

Output:

Array elements:
10
20
30
40
50

Explanation:

The loop automatically picks each element from the numbers array.

No need to use an index like numbers[i].

It’s clean, readable, and reduces the chance of index errors.

Example 2: Using for-each Loop with a List

The for-each loop is very useful when iterating over collections such as ArrayList.

import java.util.ArrayList;

public class ForEachListExample {
  public static void main(String[] args) {
    ArrayList<String> names = new ArrayList<>();
    names.add(“Alice”);
    names.add(“Bob”);
    names.add(“Charlie”);

    System.out.println(“Names in the list:”);
    for (String name : names) {
      System.out.println(name);
    }
  }
}

Output:

Names in the list:
Alice
Bob
Charlie

Explanation:

Here, each element of the ArrayList is accessed automatically by the loop. There’s no need to use get() or iterator() methods.

Example 3: Using for-each Loop with a 2D Array

You can also use nested for-each loops to iterate through multi-dimensional arrays.

public class ForEach2DArrayExample {
  public static void main(String[] args) {
    int[][] matrix = {
      {1, 2, 3},
      {4, 5, 6},
      {7, 8, 9}
    };

    System.out.println(“Matrix elements:”);
    for (int[] row : matrix) {
      for (int element : row) {
        System.out.print(element + ” “);
      }
      System.out.println();
    }
  }
}

Output:

Matrix elements:
1 2 3
4 5 6
7 8 9

Explanation:

The outer loop iterates over each row (which is itself an array).

The inner loop iterates over the elements in each row.

Key Features of for-each Loop

Feature Description:

  • Simplicity No need for index management.
  • Readability Code looks cleaner and more understandable.
  • Less error-prone Avoids off-by-one errors common in traditional for loops.
  • Read-only access You cannot modify the original collection or array element directly within the loop.
  • No index available You don’t have access to the index of the current element.
  • Limitation Example – Cannot Modify Elements
    public class

ForEachLimitationExample {
  public static void main(String[] args) {
    int[] numbers = {1, 2, 3};

    for (int num : numbers) {
      num = num * 2; // This modifies only the local copy, not the array element
    }

    for (int n : numbers) {
      System.out.print(n + ” “);
    }
  }
}

Output:

1 2 3

Explanation:

Even though we multiplied each element by 2 inside the loop, it didn’t affect the original array. The variable num is a copy of the array element, not a reference to it.

When to Use the for-each Loop

Use the for-each loop when:

  • You just want to read or display the elements of an array or collection.
  • You don’t need the index value of elements.
  • You’re working with read-only iteration (not modifying structure).

Avoid using for-each when:

  • You need to remove elements from a collection during iteration.
  • You need index-based access or modification.

Conclusion

The Java for-each loop is a powerful and elegant way to traverse arrays and collections. It helps reduce boilerplate code, making programs more readable and less error-prone. However, it’s best suited for read-only traversal since it doesn’t allow modifying the underlying data structure or accessing indexes directly.

Scroll to Top