Enhanced For Loop
Master Java's cleanest iteration syntax: the for-each loop. Learn to traverse arrays and collections with less code and fewer bugs.
What Is an Enhanced For Loop?
The enhanced for loop (also called the for-each loop) is a simplified way to iterate over every element in an array or collection. Instead of managing an index variable, a boundary condition, and an increment, you simply declare a variable and let Java hand you each element, one at a time.
Why Use the Enhanced For Loop?
The Anatomy of the Syntax
The Formal Syntax Rule
for (ElementType variable : collection) { // body executes once per element }
How It Works Under the Hood
Traditional vs Enhanced
for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); }
for (int val : arr) { System.out.println(val); }
When Not to Use It
The enhanced for loop is read-only by design. There are situations where you need the traditional loop instead:
How to Apply the Enhanced For Loop
for (Type var : collection)Example 1: Summing an Array
int[] prices = {12, 8, 25, 4, 19}; int total = 0; for (int price : prices) { total += price; } System.out.println("Total: " + total); // Output: Total: 68
Example 2: Iterating an ArrayList
ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); for (String fruit : fruits) { System.out.println(fruit.toUpperCase()); } // APPLE // BANANA // CHERRY
Example 3: Nested Loop for 2D Arrays
int[][] grid = { {1, 2, 3}, {4, 5, 6} }; for (int[] row : grid) { for (int cell : row) { System.out.print(cell + " "); } System.out.println(); } // 1 2 3 // 4 5 6
The Copy Trap: Why You Cannot Modify
int[] nums = {1, 2, 3}; for (int n : nums) { n = n * 10; // modifies the COPY, not the array! } System.out.println(Arrays.toString(nums)); // [1, 2, 3] ← unchanged!
Common Mistakes
Comparison Summary
| Feature | Traditional for | Enhanced for |
|---|---|---|
| Index access | ✓ Yes | ✕ No |
| Modify elements | ✓ Yes | ✕ No |
| Reverse iteration | ✓ Yes | ✕ No |
| Readability | Moderate | ✓ Excellent |
| Off-by-one risk | ✕ Yes | ✓ None |
| Works with Iterable | Only with .get(i) | ✓ All Iterables |
Question 1 of 5
What is the correct enhanced for loop header to iterate over String[] words?
Question 2 of 5
Given int[] vals = {3, 7, 2}, what does the following code print?
for (int v : vals) { v = v + 1; } System.out.println(vals[0]);
Question 3 of 5
Which of the following is a valid reason to use a traditional for loop instead of an enhanced for loop?
Question 4 of 5
What happens if you call list.remove(item) inside an enhanced for loop over ArrayList<String> list?
Question 5 of 5
How many times does the loop body execute?
int[][] matrix = new int[3][4]; int count = 0; for (int[] row : matrix) { for (int val : row) { count++; } }