01 / 20

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.

Java

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?

✓ Readable
The intent is immediately clear: "do something with each element."
✓ Less Error-Prone
No off-by-one mistakes, no wrong index variable, no infinite loops from a missing increment.
✓ Concise
Typically 1 line of boilerplate instead of 3 (init, condition, update).

The Anatomy of the Syntax

for ( String name : names ) { // use name here } Element type Loop variable "in" Array or Collection Read it as: "For each String name in names ..."

The Formal Syntax Rule

for (ElementType variable : collection) {
    // body executes once per element
}
1
ElementType: must match the type stored in the array or collection (e.g., int, String, Double).
2
variable: a new local variable declared just for the loop. Its scope is the loop body only.
3
collection: any array, ArrayList, or object implementing Iterable.

How It Works Under the Hood

int[] scores = {90, 85, 72, 98}; 90 [0] 85 [1] 72 [2] 98 [3] Pass 1: score = 90 → body runs with 90 Pass 2: score = 85 → body runs with 85 Pass 3: score = 72 → body runs with 72 Pass 4: score = 98 → body runs with 98 → loop ends

Traditional vs Enhanced

Traditional for
for (int i = 0; i < arr.length; i++) {
  System.out.println(arr[i]);
}
Enhanced for
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:

1
Modifying elements in place: Assigning to the loop variable does not change the original array.
2
Needing the index: If you need to know the position of each element, you have no index variable.
3
Iterating in reverse or skipping elements: The enhanced for loop always goes forward, one element at a time.
4
Iterating over multiple collections simultaneously: You cannot zip two arrays together with one enhanced for loop.

How to Apply the Enhanced For Loop

1
Identify the collection: Is it an array, ArrayList, or other Iterable?
2
Determine the element type: What type does the collection store? (int, String, Object, etc.)
3
Choose a descriptive variable name: Use a singular noun that matches the collection (e.g., name for names).
4
Write the loop header: for (Type var : collection)
5
Write the loop body: Use the variable to read each element. Remember: changes to the variable do not affect the 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!
Array (original) 1 2 3 copy Loop variable (n) 10 ✕ Does not write back ✓ Array remains [1, 2, 3]

Common Mistakes

✕ Wrong Type
Using int for an ArrayList<String>. The element type must match the collection's stored type exactly.
✕ Modifying via Variable
Assigning to the loop variable (e.g., n = 0) and expecting the array to change. It only modifies the local copy.
✕ Removing During Iteration
Calling .remove() on a collection inside an enhanced for loop causes a ConcurrentModificationException.

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++;
    }
}