The for-each loop in Java is a simplified looping structure used to iterate over arrays and collections without using indexes.
The loop automatically accesses each element in sequence.
// General syntax of for-each loop
for(dataType variable : collection){
// statements using variable
}
// Example of for-each loop with array
class Main {
public static void main(String[] args) {
int[] numbers = {10,20,30,40};
// Loop through each element
for(int num : numbers){
System.out.println(num);
}
}
}
10
20
30
40
The loop picks one value at a time from the array and prints it.
Scenario: Calculate Sum using for-each
int[] data = { 5, 12, 8, 20 };