Core Java Fundamentals ยท Loops

Enhanced For Loop (For-Each)

Learn a simpler way to iterate over arrays and collections using the enhanced for loop, also known as the for-each loop.

ForEachDemo.java

public class ForEachDemo {
    public static void main(String[] args) {
        // An array of integers
        int[] numbers = {10, 20, 30, 40};
        int sum = 0;

        System.out.println("Iterating through the array:");

        // Enhanced for loop to iterate through 'numbers'
        for (int number : numbers) {
            System.out.println("Current number: " + number);
            sum += number;
        }

        System.out.println("Sum of all numbers: " + sum);
    }
}

Step by step

  1. The program starts. We declare an integer array numbers and initialize it with five values. This array is created in the heap memory.
  2. We declare an integer variable sum and initialize it to 0. This will be used to store the sum of the array elements.
  3. A string is printed to the console to indicate the start of the iteration.
  4. The enhanced for loop begins. It will iterate through each element of the numbers array one by one.
  5. Iteration 1: The first element (10) from numbers is assigned to the loop variable number.
  6. The current value of number (10) is printed to the console.
  7. The value of number (10) is added to sum. sum is now 10.
  8. Iteration 2: The next element (20) is assigned to number.
  9. The current value of number (20) is printed.
  10. The value of number (20) is added to sum. sum is now 30.
  11. Iteration 3: The next element (30) is assigned to number.
  12. The current value of number (30) is printed.
  13. The value of number (30) is added to sum. sum is now 60.
  14. Iteration 4: The next element (40) is assigned to number.
  15. The current value of number (40) is printed.
  16. The value of number (40) is added to sum. sum is now 100.
  17. The loop has processed all elements in the numbers array and now terminates. The number variable goes out of scope.
  18. The final sum is printed to the console.