Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Video lesson

Understanding for-each loop in Java

In this lesson, you will learn

  • For-Each Loop in Java
  • Examples

 

What is the For-Each Loop in Java?

  • The for-each loop is a simplified way to iterate over elements in arrays and collections (like lists) in Java.
  • It eliminates the need for explicit index management, making your code cleaner and less error-prone.
  • It’s particularly useful when you want to process each element in a sequence without needing to know its position.

Syntax:

for (elementType elementVariable : arrayOrCollection) {
    // Code to be executed for each element
    // elementVariable holds the current element's value
}

  • elementType: The data type of the elements in the array or collection.
  • elementVariable: A variable that will hold the value of each element during each iteration.
  • arrayOrCollection: The array or collection you want to iterate over.

 

How to Use For-Each Loop for 1D Arrays:

public class ForEach1DArray {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};

        System.out.println("Elements of the array:");
        for (int number : numbers) {
            System.out.println(number);
        }

        // Example of summing the elements
        int sum = 0;
        for (int number : numbers) {
            sum += number;
        }
        System.out.println("Sum of the elements: " + sum);
    }
}

Output

Elements of the array:
1
2
3
4
5
Sum of the elements: 15


 

How to Use For-Each Loop for 2D Arrays:

When using a for-each loop with a 2D array, you’ll need nested loops. The outer loop iterates over the rows, and the inner loop iterates over the elements in each row.

public class ForEach2DArray {
    public static void main(String[] args) {
        int[][] matrix = {
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}
        };

        System.out.println("Elements of the 2D array:");
        for (int[] row : matrix) { // Outer loop: iterates through rows
            for (int element : row) { // Inner loop: iterates through elements in each row
                System.out.print(element + " ");
            }
            System.out.println(); // Move to the next line after each row
        }

        //Example of summing all elements in the 2D array.
        int totalSum = 0;
        for (int[] row : matrix){
            for(int element : row){
                totalSum+=element;
            }
        }
        System.out.println("The total sum of all elements is: " + totalSum);
    }
}


Output

Elements of the 2D array:
1 2 3 
4 5 6 
7 8 9 
The total sum of all elements is: 45

 

Key Advantages of For-Each Loop:

  • Readability: It makes code cleaner and easier to understand.
  • Reduced Errors: It eliminates the risk of off-by-one errors that can occur when using traditional for loops with indices.
  • Simplicity: It simplifies iteration over arrays and collections.

Limitations:

  • You cannot modify the elements of the array or collection directly within the loop.
  • You cannot access the index of the current element.
  • You cannot iterate in reverse.

 

Therefore, to take user input and store it in an array, you’ll need to use a traditional for loop with an index. Here’s a breakdown and example:

Why For-Each Doesn’t Work for Input:

  • Read-Only Access:
    • The for-each loop provides a copy of each element’s value to the loop variable.
    • Modifying that loop variable does not change the original array element.

How to Take User Input and Store in an Array:

Here’s the correct way to do it using a standard for loop:

import java.util.Scanner;

public class ArrayUserInput {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the size of the array: ");
        int size = scanner.nextInt();

        int[] numbers = new int[size];

        System.out.println("Enter " + size + " numbers:");

        // Use a traditional for loop to take input
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = scanner.nextInt();
        }

        System.out.println("Array elements:");

        // Now, you can use a for-each loop to display the array
        for (int number : numbers) {
            System.out.print(number + " ");
        }
        System.out.println();

        scanner.close();
    }
}

Output

Enter the size of the array: 5
Enter 5 numbers:
4
5
6
7
8
Array elements:
4 5 6 7 8 


 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

3.0
3.0 out of 5 stars (based on 1 review)
Excellent0%
Very good0%
Average100%
Poor0%
Terrible0%

 

 

30/10/2025

There is some overlapping of the content making it bit unreadable. Please verify.

 

 

Submit a Review