Open In App

For-Each Loop in Java

Last Updated : 18 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The for-each loop in Java (also called the enhanced for loop) was introduced in Java 5 to simplify iteration over arrays and collections. It is cleaner and more readable than the traditional for loop and is commonly used when the exact index of an element is not required.

Example:

Below is a basic example of using the for-each loop to iterate through an array and print each element. A for-each loop directly accesses elements without needing index variables.

// Java Program to Iterate through an array
// Using for-each loop
import java.io.*;

class ForEach {
  
    public static void main(String[] args) {
      
        // Array declaration
        int arr[] = { 1, 2, 3, 4, 5 };
        
        // Using for-each loop to 
        // print each element
        for (int e : arr) {
            System.out.print(e + " ");
        }
    }
}

Output
1 2 3 4 5 

Explanation: In this example, the for-each loop iterates over the array “arr" and prints each element. We use the variable element "e" to access each value in the array, making the loop more concise compared to using a traditional for loop with an index.

Syntax of For-each Loop

for (type var : array) {

statements using var;

}

Parameters:

  • type: The data type of the elements in the array or collection.
  • var: The variable that holds the current element during each iteration.
  • array: The array or collection being iterated over.

Finding Maximum in an Array using for-each Loop

Now, let’s go through another example that finds the maximum value in an integer array using a for-each loop.

// Java Program to find maximum in an array
// Using for-each loop
public class Maximum {
  
    public static void main(String[] args) {
      
        int[] mark = {125, 132, 95, 116, 110};

        int max = findMax(mark);
        System.out.println("" + max);
    }

    public static int findMax(int[] n) {
        int maximum = n[0];

        // Iterates through the array
        for (int n1: n) {        
            if (n1 > maximum) {
                maximum = n1;
            }
        }
        return maximum;
    }
}

Output
132

Limitations of the For-each Loop

While the for-each loop is convenient, there are some important limitations to consider:

1. Cannot Modify Array Elements Directly

for (int num : marks) {

// only changes num, not the array element
num = num*2;

}

Explanation: The for-each loop gives a copy of each element, not a reference. So modifying the loop variable (num in this case) does not affect the actual array or collection.

2. No Access to Index

for (int num : numbers) {

if (num == target) {

// do not know the index of ‘num’ here

return ???; // Index is unavailable in for-each loop

}

}

Explanation: The for-each loop does not provide access to the index of the current element. If we need the index for any reason (e.g., in a search operation), a traditional loop would be more appropriate.

3. Single-direction Iteration Only

for (int i = numbers.length – 1; i >= 0; i–) {

System.out.println(numbers[i]); // Reverse iteration not possible with for-each

}

Explanation: The for-each loop only iterates over the elements in a forward direction. If we need to iterate in reverse, we have to use a traditional for loop with a manually managed index.

4. Complex Conditions are Difficult to Implement

for (int i = 0; i < numbers.length; i++) {

if (numbers[i] == arr[i]) {

// Complex conditional checks are easier in a traditional for loop

}

}

Explanation: If our logic requires checking multiple conditions or using the index in more complex ways, the for-each loop can be limiting. In such cases, a traditional for loop offers more flexibility.

5. Performance Overhead

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

for (int i = 0; i < 1000000; i++) list.add(i);


// Using for-each loop

long startTime = System.currentTimeMillis();

for (int i : list) { int a = i; }

long endTime = System.currentTimeMillis();

System.out.println(“For-each loop: ” + (endTime – startTime) + ” ms”);


// Traditional loop

startTime = System.currentTimeMillis();

for (int i = 0; i < list.size(); i++) { int a = list.get(i); }

endTime = System.currentTimeMillis();

System.out.println(“Traditional loop: ” + (endTime – startTime) + ” ms”);

Explanation: The for-each loop sometimes might be slower compared to traditional for loops because for iterating over collections it uses an iterator internally.

Example:

// Java program to compare the performance of 
// different loop types for 
// iterating over a large list
import java.io.*;
import java.util.*;

class Geeks 
{
    public static void main(String[] args) 
    {

        List<Integer> list = new ArrayList<>();
        long startTime;
        long endTime;

        // Adding 1 million integers to the list
        for (int i = 0; i < 1000000; i++) 
        {
            list.add(i);
        }

        // Type 1: Using a for-each loop
        startTime = Calendar.getInstance().getTimeInMillis();
        for (int i : list) 
        {
            // Looping over each element
            int a = i;
        }
        endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("For each loop :: " + (endTime - startTime) + " ms");

        // Type 2: Using list.size() in the loop condition (with precomputation)
        startTime = Calendar.getInstance().getTimeInMillis();
        int size = list.size();
        for (int j = 0; j < size; j++) 
        {
            // Accessing list elements using index
            int a = list.get(j);
        }
        endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("Using collection.size() (precomputed) :: " + 
        (endTime - startTime) + " ms");

        // Type 3: Calculating the collection size before the loop (already optimized)
        startTime = Calendar.getInstance().getTimeInMillis();
        for (int j = 0; j < size; j++) 
        {
            // Accessing list elements using index
            int a = list.get(j);
        }
        endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("By calculating collection.size() first :: " + 
        (endTime - startTime) + " ms");

        // Type 4: Iterating the list in reverse order
        startTime = Calendar.getInstance().getTimeInMillis();
        for (int j = size - 1; j >= 0; j--) {
            // Accessing list elements in reverse
            int a = list.get(j);
        }
        endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("Using [int j = size - 1; j >= 0; j--] (precomputed) :: " +
        (endTime - startTime) + " ms");
    }
}

Output
For each loop :: 42 ms
Using collection.size() (precomputed) :: 13 ms
By calculating collection.size() first :: 13 ms
Using [int j = size - 1; j >= 0; j--] (precomputed) :: 23 ms

Explanation: Each time we run the above code it will give a different output because the execution and the performance times depend on different factors when JVM starts it takes time to optimize so it might appear that the loops work differently. as mentioned the for-each loop uses iterator internally which make a slight performance overhead compared to the traditional for loop.

Points to Remember:

  • The loop starts with the keyword for like a normal for-loop.
  • Instead of declaring and initializing a loop counter variable, we declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name.
  • In the loop body, we can use the loop variable we created rather than using an indexed array element.
  • It is commonly used to iterate over an array or a Collections class (e.g., ArrayList)
     


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg