01 / 21

For-Each Loops
in Java

Master the enhanced for loop to iterate over arrays and collections with cleaner, safer code.

Java AP Computer Science A

What Is a For-Each Loop?

A for-each loop (also called an enhanced for loop) is a simplified way to iterate through every element in an array or collection. Instead of managing an index variable, the loop automatically hands you each element, one at a time.

How the Loop Traverses an Array

[0] [1] [2] [3] [4] 10 25 37 42 58 current element num Each iteration copies the next element into num

On each iteration, the loop copies the next element from the array into the loop variable. No index needed: Java handles the traversal automatically.

Why Use a For-Each Loop?

✓ Readability
Less code to write and read: no index variable, no bounds checking, no .length.
✓ Safety
Eliminates off-by-one errors and ArrayIndexOutOfBoundsException.
✓ Universality
Works with arrays, ArrayList, HashSet, and any Iterable.

The Syntax

for (Type variable : collection) { // body: use variable }
Type
The data type of each element (e.g., int, String).
variable
A new name that holds the current element each iteration.
collection
The array or Iterable being traversed.

Anatomy of a For-Each Statement

for ( int num : scores ) { keyword element type loop variable "in" array / collection Read as: "for each int num in scores"

Traditional For vs For-Each

// Traditional for loop for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } // Enhanced for-each loop for (int val : arr) { System.out.println(val); }

When Not to Use For-Each

The for-each loop is read-only over the collection. Use a traditional for loop when you need to:

1
Modify elements: Assigning to the loop variable does not change the original array.
2
Track the index: You have no access to the current position i.
3
Traverse in reverse: For-each always goes forward, from index 0 to the end.
4
Compare adjacent elements: You can only see one element at a time.

How to Write a For-Each Loop

1
Identify the collection: What array or ArrayList are you iterating over?
2
Determine the element type: What is stored in each slot? (int, String, double, an object?)
3
Name the loop variable: Choose a meaningful name (e.g., name for a String[] of names).
4
Write the body: Use the loop variable directly: no [i] needed.
5
Check your goal: If you need to modify elements or use the index, switch to a traditional for loop.

Example: Summing an Array

int[] scores = {88, 92, 75, 100, 67}; int total = 0; for (int score : scores) { total += score; } System.out.println(total); // 422

Example: Searching for a Value

String[] fruits = {"apple", "banana", "cherry"}; boolean found = false; for (String fruit : fruits) { if (fruit.equals("banana")) { found = true; } } System.out.println(found); // true

Example: Iterating an ArrayList

ArrayList<Double> temps = new ArrayList<>(); temps.add(98.6); temps.add(99.1); temps.add(97.8); double max = temps.get(0); for (double t : temps) { if (t > max) { max = t; } } System.out.println(max); // 99.1

The Read-Only Trap

int[] nums = {1, 2, 3}; for (int n : nums) { n = n * 2; // Does NOT modify the array! } System.out.println(Arrays.toString(nums)); // Output: [1, 2, 3] ← unchanged!
Original Array 1 2 3 copies value n = 2 ✕ change lost To Modify: Use Index for ( int i=0; ... ) { nums[i] = nums[i]*2; } // [2, 4, 6] ✓ ✓

For-Each with 2D Arrays

int[][] grid = { {1, 2, 3}, {4, 5, 6} }; for (int[] row : grid) { // outer: each row for (int val : row) { // inner: each element System.out.print(val + " "); } } // Output: 1 2 3 4 5 6

Common Mistakes

✕ Wrong Type
Using int when iterating a String[]. The loop variable type must match the element type.
✕ Modifying Elements
Attempting to modify the array by assigning to the loop variable. This fails because the variable is a copy of the element's value (for primitives) or reference (for objects).
✕ Using Index Syntax
Writing arr[val] inside the loop. The variable already is the element, not an index.

Comparison Summary

Traditional For For-Each
Syntax complexity 3 parts (init, condition, update) 1 declaration + collection
Index access ✓ Yes ✕ No
Modify elements ✓ Yes ✕ No (primitives)
Reverse traversal ✓ Yes ✕ No
Risk of off-by-one High None
Works with ArrayList ✓ Yes ✓ Yes
Best for Full control over iteration Simple read-only traversal

Question 1 of 5

What is the output of the following code?

int[] a = {3, 7, 1}; int sum = 0; for (int x : a) { sum += x; } System.out.println(sum);

Question 2 of 5

Which of the following is a limitation of the for-each loop?

Question 3 of 5

What should replace ??? to correctly iterate over a String[] array called names?

for (???) { System.out.println(name); }

Question 4 of 5

What is the output of this code?

int[] vals = {10, 20, 30}; for (int v : vals) { v = v + 5; } System.out.println(vals[0]);

Question 5 of 5

To iterate over a 2D int array called grid, what type should the outer loop variable be?