Java Foreach

Summary: in this tutorial, you will learn how to use the Java Foreach loop to iterate over elements of an array or collection.

Introduction to the Java Foreach loop #

To iterate over elements of an array, you often use a for loop. For example:

double[] amounts = { 9.99, 10.25, 7.89 };

for (int i = 0; i < amounts.length; i++) {
   System.out.println(amounts[i]);
}

In the for loop:

  • First, initialize a loop variable i that represents the index of the element of the array.
  • Second, access the array element by the index i, display it, and increase the loop variable i by one to advance to the next index in each iteration.
  • Third, continue the loop as long as the loop variable i is less than the number of elements of the array.

The for loop works fine. But it has some issues:

  • Index management: You need to manage the loop variable, which serves as the array index, yourself. If you do it incorrectly, you’ll get an exception.
  • Code clutter: The for loop makes the code more cluttered, especially with complex logic within the loop body.
  • Limited abstraction: The for loop exposes very low-level control over the iteration process.

To address these issues, Java 8 introduced an enhanced for loop, which is often called a Foreach loop.

Here’s the syntax of the Foreach loop:

for(dataType element: array) {
    // ...
}

In this syntax;

  • dataType specifies the data type of the element of the array.
  • element is a variable that holds each element in the array during iteration.
  • array is the array to be iterated.

Since Java can infer the type of the array element, you can use the var keyword to make the code more concise:

for(var element: array) {
    // ...
}

For example, the iterate over elements of the amounts array above, you can use a Foreach loop as follows:

double[] amounts = {9.99, 10.25, 7.89};

for(var amount: amounts) {
    System.out.println(amount);
}

Summary #

  • Use a Foreach loop to iterate over elements of an array or a collection to make code more concise.

Was this helpful?