Java for-each Loop

Java for-each Loop

In this tutorial, we will learn about another form of for loop in Java known as enhanced for loop or for each loop with the help of examples.

In Java, while working with arrays and collections, we can use the enhanced form of for loop. It is also known as a for-each loop. It is because the loop iterates through each element of arrays or collections.

Before you learn about the for-each loop, make sure you know about:


Difference between for loop and for-each loop

To know why the for-each loop is preferred over for loop while working with arrays, let's see the following example.

Here the example shows how we can iterate through elements of an array using the standard for loop.

class ForLoop {
    public static void main(String[] args) {
      
        char[] vowels = {'a', 'e', 'i', 'o', 'u'};

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

Output:

a
e
i
o
u

Now we will perform the same task using the for-each loop.

class AssignmentOperator {
   public static void main(String[] args) {
      
      char[] vowels = {'a', 'e', 'i', 'o', 'u'};
      // foreach loop
      for (char item: vowels) {
         System.out.println(item);
      }
   }
}

Output:

a
e
i
o
u

Here, we can see that the output of both the program is the same.

When we carefully analyze both the program, we can notice that the for-each loop is easier to write and makes our code more readable. This is the reason it is called enhanced for loop.

Hence, it is recommended to use the enhanced for loop over the standard for loop whenever possible.


Java for-each loop

Let's first look at the syntax of for each loop:

for(data_type item : collections) {
    ...
}

Here,

  • collection - a collection or array that you have to loop through.
  • item - a single item from the collections.

How for-each loop works?

Here's how the for-each loop works in Java. For each iteration, the for-each loop

  • iterates through each item in given collections or arrays (collections),
  • stores each item in a variable (item)
  • and executes the body of the loop.

Let's make it clear through an example.

Example: for-each loop

The program below calculates the sum of all elements of an integer array.

class EnhancedForLoop {
    public static void main(String[] args) {
      
        int[] numbers = {3, 4, 5, -5, 0, 12};
        int sum = 0;
      
        for (int number: numbers) {
            sum += number;
        }
      
        System.out.println("Sum = " + sum);
    }
}

Output:

Sum = 19

In the above program, the execution of the for-each loop looks as:

Iteration Value
1 number = 3 and sum = 0 + 3 = 3
2 number = 4 and sum = 3 + 4 = 7
3 number = 5 and sum = 7 + 5 = 12
4 number = -5 and sum = 12 + (-5) = 7
5 number = 0 and sum = 7 + 0 = 7
6 number = 12 and sum = 7 + 12 = 19

You can see during each iteration, the for-each loop

  • iterates through each element in the numbers array
  • stores it in the number variable
  • and executes the body, i.e. adds the number to sum