For-each loop in Java

For-each loop in Java

Loops are a fundamental concept in Java that allows you to execute a block of code repeatedly. Java provides us with three main types of loops: for loop, while loop, and do-while loop to iterate through elements in an array or a collection. The for-each loop is an extended version of the for-loop that is used to iterate through an array or collection without the need for an index.

In this blog, we will learn about for each loop, its working, features, and examples in more detail.

Table of Contents:

What is for each Loop in Java?

The for-each loop, also known as the enhanced for loop in Java, is used to iterate through elements in an array or a collection without using an index variable. It was introduced in Java 5 to simplify the traversal of collections and arrays.

Syntax of For-each Loop

The syntax of the for-each loop is as follows:

for (dataType item: array/Collection) {
    // body of loop
}

Parameters:

  • dataType: The type of elements in the array or collection.
  • item: A variable representing each element in the array or collection.
  • arrayOrCollection: The array or collection to be iterated over.

How Does For-each Loop Work?

The for-each loop (also known as the enhanced for loop) in Java is a control flow statement used to iterate over arrays and collections. It is used to simplify the traversal of elements without using an index.

Let’s understand the workings of for each loop with the below example:

for (int num: numbers) {
            System.out.println(num);
        }
  • Step 1: The loop automatically retrieves each element from the array or collection one by one, starting from the first element to the last.
  • Step 2: In every iteration, the current element is assigned to the loop variable.
  • Step 3: You can use the loop variable inside the loop to perform operations like printing, calculations, etc.
  • Step 4: Moves to the Next Element: After processing the current element, the loop moves to the next element until all elements are traversed.

Example:

Java

Let’s learn the workings of the for-each loop in the above code:

  • Before the loop starts:
    • sum is initialized to 0.
  • 1st Iteration:
    • num = 1
    • sum += num then, sum = 0 + 1 = 1
  • 2nd Iteration:
    • num = 2
    • sum += num then, sum = 1 + 2 = 3
  • 3rd Iteration:
    • num = 3
    • sum += num then, sum = 3 + 3 = 6
  • 4th Iteration:
    • num = 4
    • sum += num then, sum = 6 + 4 = 10
  • 5th Iteration:
    • num = 5
    • sum += num then, sum = 10 + 5 = 15
  • 6th Iteration:
    • num = 6
    • sum += num then, sum = 15 + 6 = 21
  • After the loop ends:
    • System.out.println(sum) prints 21.

Examples of For-each Loop in Java

Here are the following examples of the for-each loop in Java:

1. Print Array Elements

In this example, we are going to print the array elements using for-each loop in Java:

Example:

Java

Output:

2. Sum of Array Elements

In this example, we are going to find the sum of all the array elements using for-each loop in Java:

Example:

Java

Output:

3. Traversing Collection Elements

In this example, we are going to traverse all elements of a collection using for-each loop in Java:

Example:

Java

Output:

4. Finding Maximum in an Array

In this example, we are going to find the maximum of all the elements in an array  using for-each loop in Java:

Example:

Java

Output:

For Loop vs For-each Loop

The main difference between the for loop and for-each loop is that the for loop uses an index for accessing the elements of the array or collection, while the for-each loop doesn’t use an index.

Let’s learn this concept with the help of one example as we are going to use the example of an integer array and then run both for loop and for each to compare them. 

Example 1: Printing the element of Integer Array using traditional for loop

Java

Output:

Example 2: Printing the element of Integer Array using for each loop

Java

Output:

Key Differences Explained with Examples

For LoopFor-each Loop
We need the index of elements while traversing the array.We don’t need the index of elements while traversing the array.
We can modify the elements of the array.We can not modify the elements of the array directly.
Its syntax is more complex compared to the for-each loop.Its syntax is simple and more readable

For each Loop with Multidimensional Arrays

The for-each loop in Java can also be used to traverse elements of multidimensional arrays. However, since the for-each loop does not provide direct access to indices, it iterates over the sub-arrays first before accessing individual elements.

Example: Iterating Over a 2D Array

Java

Output:

Exception Handling Within For-each Loops

In Java, exceptions can occur inside a for-each loop, just like in any other loop. However, handling exceptions within a for-each loop requires careful consideration to avoid breaking the entire iteration.

Example:

Java

Output:

Explanation: The above code iterates through an array of strings and prints the length of each word. If a null value is encountered, it catches the NullPointerException and prints “Null value encountered” instead of stopping execution.

Integrating For-each Loop with Java Streams

Java Streams work well with for-each loops when processing collections.

Example:

Java

Output:

Explanation:

  • stream().forEach() is a functional way to iterate over collections.
  • Unlike a traditional for-each loop, forEach() in a stream is often used in parallel processing.

Advantages of For-each Loop in Java

Here are the following advantages of the for-each loop in Java:

  • It is easy to write and understand.
  • It reduces the code complexity.
  • It is better than for loop, as it does not give IndexOutOfBoundsException error.

Limitations of For-each Loop in Java

Here are the following limitations of the for-each loop in Java:

1. We can not modify the elements directly.

for(int num: numbers)
{
  //only num is updated, not the array element,
   num = num+10;
}

Explanation: In the above code, when we try to update the value of num, it only updates the value of num, not the array elements. Because for-each loop only gives us the copy of the values, not a reference to that element. 

2. We can not access the elements by their index.

Suppose, we have to find the index of the smallest element in an array, then for-each loop can not give us the index of that element.

for (int num : numbers) {
    if (num < min) {
        min = num;
        // We cannot update minIndex because we do not have access to the index
        minIndex = ???;  // Index is unavailable in for-each loop
    }
}

3. Single-direction Iteration Only

The for-each loop does not allow backward iteration at all, but the for loop can iterate in both directions.

3.1 for-each loop allows only single-direction iteration

for (int num : numbers) {
    // No way to go backward
    System.out.println(num);
}

3.2 for loop allows both forward and backward iteration

for (int i = numbers.length - 1; i >= 0; i--) {
    System.out.println(numbers[i]);
}

4. Complex Conditions are Difficult to Implement

When our code requires some conditions to check inside a loop, the for-each loop does not provide enough flexibility to handle complex conditions effectively.

Example: Compare the elements of two array

4.1 Using for-each loop

int[] arr1 = {10, 20, 30, 40};
int[] arr2 = {10, 25, 30, 50};
for (int num : arr2) {
// No way to access the corresponding index in arr1
    if (num == arr1[???]) {  
        System.out.println("Match found");
    }
}

4.2 Using for loop

int[] arr1 = {10, 20, 30, 40};
int[] arr2 = {10, 25, 30, 50};
for (int i = 0; i < arr2.length; i++) {
    if (arr2[i] == arr1[i]) {  
      // Now we can access corresponding indices
        System.out.println("Match found at index " + i);
    }
}

Points to Remember

  • The syntax of the for-each loop starts with the for keyword.
  • It is used to iterate through an array or list.
  • We don’t need to create a variable, check the condition, and increment the variable in each iteration like a traditional for loop. We just need a variable for iterating the array.
  • In the loop body, we just use that variable and do the required operations.

Conclusion

So far in this article, we have learned the workings of for each loop in Java. for-each loop is used for traversing elements in arrays and collections, providing better readability and reducing the possibility of error. It has limitations in that we can not modify the elements directly, also we can’t access the elements with the help of an index. If you want to learn more about Java, you may refer to our Java Programming Course.

Frequently Asked Questions (FAQs)

1. What are loops in programming?

Loops in programming are used to repeat a set of instructions multiple times. Instead of writing the same code again and again, you can use a loop to run it automatically until a condition is et.

2. What are the different types of loops in Java?

There are the following types of loops in Java:

  • for loop
  • while loop
  • do-while loop
  • for-each loop
3. What are the uses of loops in programming?

Loops are used in programming to repeat tasks and process data in lists or arrays.

4. Where for-each loop is used?

The for-each loop is mainly used to iterate over arrays and collections (like lists or sets).

5. What is the time complexity of for each loop?

The time complexity of for each loop is O(n).

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner