Java for-each Loop

In this tutorial, we will learn about the Java for-each loop and its difference with for loop with the help of examples.

In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList). It is also known as the enhanced for loop.

for-each Loop Syntax

The syntax of the Java for-each loop is:

for(dataType item : array) {
    ...
}

Here,

  • array - an array or a collection
  • item - each item of array/collection is assigned to this variable
  • dataType - the data type of the array/collection

Example 1: Print Array Elements

// print array elements
class Main {
  public static void main(String[] args) {

    // create an array
    int[] numbers = {3, 9, 5, -5};

    // for each loop
    for (int number: numbers) {
      System.out.println(number);
    }
  }
}

Output:

3
9
5
-5

2. Iterating over Collections

The enhanced for loop is perfect for iterating over collections like ArrayList.

import java.util.ArrayList;

class Main {
    public static void main(String[] args) {
        ArrayList<String> animals = new ArrayList<>();
        animals.add("Dog");
        animals.add("Cat");
        animals.add("Horse");

        for (String animal : animals) {
            System.out.println(animal);
        }
    }
}

Output:

Dog
Cat
Horse

3. for loop Vs for-each loop

Let's see how a for-each loop is different from a regular Java for loop.

1. Using for loop

char[] vowels = {'a', 'e', 'i', 'o', 'u'};

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

2. Using for-each Loop

char[] vowels = {'a', 'e', 'i', 'o', 'u'};

for (char item: vowels) {
  System.out.println(item);
}

Here, the output of both programs is the same. However, the for-each loop is easier to write and understand.

Can you use a for-each loop to modify elements in the original array?

Tip 💡: The enhanced for-loop is great for reading data, but you can't use it to modify the original array (like doubling every number). For that, stick to the classic for loop!


Key Takeaways

  • Syntax: for (Type item : collection).
  • Read-Only: You cannot modify the array/collection structure (add/remove) while iterating.
  • Simplicity: No need to manage index variables i.

Common Pitfalls

[!WARNING] Modification: Trying to modify the collection (e.g., list.remove(item)) inside a for-each loop will throw a ConcurrentModificationException. Use an Iterator instead.

Challenge

Challenge

Task:

Use an enhanced for loop to print each name in the array {'Alice', 'Bob', 'Charlie'}.