Core Java Fundamentals ยท Loops
Learn a simpler way to iterate over arrays and collections using the enhanced for loop, also known as the for-each loop.
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);
}
}numbers and initialize it with five values. This array is created in the heap memory.sum and initialize it to 0. This will be used to store the sum of the array elements.numbers array one by one.numbers is assigned to the loop variable number.number (10) is printed to the console.number (10) is added to sum. sum is now 10.number.number (20) is printed.number (20) is added to sum. sum is now 30.number.number (30) is printed.number (30) is added to sum. sum is now 60.number.number (40) is printed.number (40) is added to sum. sum is now 100.numbers array and now terminates. The number variable goes out of scope.