Careeroza
for-each Loop
Looping Over Elements
The enhanced for (for-each) loop visits every element of an array or collection without an index variable.
Example
import java.util.List;
public class Main {
public static void main(String[] args) {
String[] cities = {"Delhi", "Mumbai", "Kolkata", "Chennai"};
for (String city : cities) {
System.out.println(city);
}
int[] prices = {120, 80, 250};
int total = 0;
for (int price : prices) {
total += price;
}
System.out.println("Total: " + total);
List<String> skills = List.of("Java", "SQL", "Spring");
for (String skill : skills) {
System.out.print(skill + " ");
}
System.out.println();
}
}Output
Delhi Mumbai Kolkata Chennai Total: 450 Java SQL Spring
for vs for-each
| Need | Use |
|---|---|
| Just read every element | for-each |
| The index (position) | classic for |
| Go backwards or skip elements | classic for |
| Change array elements | classic for (arr[i] = ...) |
Note: Assigning to the for-each variable does not change the array: in for (int p : prices) p = 0; only the copy changes.