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

NeedUse
Just read every elementfor-each
The index (position)classic for
Go backwards or skip elementsclassic for
Change array elementsclassic 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.