The for each loop

The for each loop or enhanced for loop is the simplest way to iterate through all the elements of an array or a collection. For each loop is much similar to other loops available in Java like – For loop, while loop and do while loop but here we don’t need to specify any condition variable, the for each loop runs until it reaches the last most element of a given array or collection.

Syntax

for (<type> <variable> : <array or collect>) {
    // Loop body
}

Example with array

public class ForEachArray {

    public static void main(String[] args) {

        int numbers[] = {10, 20, 30, 40, 50};

        for (int num : numbers) {
            System.out.println(num);
        }

    }
}

Explanation

In the above example, we have declared and initialized one integer array (numbers) with 5 elements and then we have passed that array to the for each loop. In every iteration, each element is assigned to the variable (num) and then control comes inside the loop body.

Points to note

  1. For each loop does not keep track current index of an element.
  2. It can only iterate in forwarding direction.
  3. It can be used with an array or collection.
  4. Difficult to change the value of an element since it does not keep track of the index.

Example with collection

import java.util.ArrayList;

public class ForEachCollection {

    public static void main(String[] args) {

        ArrayList<Integer> list = new ArrayList<>();

        list.add(10);
        list.add(20);
        list.add(30);
        list.add(40);
        list.add(50);

        for (int item : list) {
            System.out.println(item);
        }

    }
}