Java • Collections and Strings

Enhanced For Loop — Iterate collections with enhanced for loop

Simplify your iteration code by letting Java handle the indexing for you.

Java programming emblem with a coffee cup, code braces, and terminal
Inside this lesson 10 sections 5 questions 7 figures

SECTION 1

Historical Context & Motivation

Before the enhanced for loop existed, Java programmers had to write verbose code just to walk through every item in an array or collection. You needed an index variable, a boundary check, and a manual increment — three things that could each introduce bugs. As Java matured, the language designers looked for ways to reduce this boilerplate and make everyday tasks safer and more readable.

1996 • Java 1.0 — Manual Indexing Only

Developers relied on the traditional for (int i = 0; i < arr.length; i++) pattern to iterate arrays. The Enumeration interface handled early collections, but its syntax was clunky.

1998 • Java 1.2 — Collections Framework

The Iterator interface replaced Enumeration, giving collections a standard traversal mechanism via hasNext() and next(). However, programmers still had to write several lines of setup code.

2004 • Java 5 — Enhanced For Loop Arrives

Java 5 (also called J2SE 5.0) introduced the for-each loop alongside generics and autoboxing. This single syntactic addition eliminated the most common source of off-by-one errors and made code dramatically more readable.

2014 • Java 8 — Streams & forEach()

Lambda expressions and the Streams API introduced forEach() as a functional alternative. The enhanced for loop remained the go-to for simple, imperative iteration.

The core question the enhanced for loop answers is straightforward: How can we visit every element in a collection without worrying about indices, bounds, or iterator boilerplate? Understanding this construct is essential for writing clean, modern Java.

SECTION 2

Core Principles & Definitions

The enhanced for loop — commonly called the for-each loop — is a streamlined way to iterate over every element in an array or any object that implements the Iterable interface. Instead of managing an index variable yourself, you declare a loop variable that automatically takes on the value of each element, one at a time.

1

Syntax

Written as for (Type item : collection). The colon (":") is read as "in." The loop variable item receives a copy of each element on every pass through the loop.
2

Works with Arrays

Any Java array — whether it holds primitives like int[] or objects like String[] — can be traversed with an enhanced for loop. No .length or index needed.
3

Works with Collections

Any class implementing Iterable<T> — such as ArrayList, HashSet, and LinkedList — works seamlessly with the for-each loop.
4

Read-Only Access

The loop variable is a copy of the element. Reassigning it does not modify the original array or collection. You cannot add or remove elements during iteration without special handling.
✦

KEY TAKEAWAY

Think of the enhanced for loop like a conveyor belt at a sushi restaurant. Each plate (element) slides in front of you automatically — you don't have to count which plate number you're on or worry about reaching past the last one. You just grab what's in front of you and process it.

SECTION 3

Visual Explanation

Enhanced For Loop — Step-by-Step ExecutionString[] fruits = {"Apple", "Banana", "Cherry", "Date"};for (String f : fruits) { System.out.println(f); }Array: fruits"Apple"index 0"Banana"index 1"Cherry"index 2"Date"index 3Loop Iterations:f = "Apple"f = "Banana"f = "Cherry"f = "Date"Pass 1Pass 2Pass 3Pass 4
Each pass through the loop assigns the next element to the variable f. The programmer never references an index — Java handles the progression automatically, stopping when the last element has been visited.

In the diagram above, notice that the array has four elements. The enhanced for loop runs exactly four times — once for each element. On the first pass, f holds "Apple"; on the second pass, it holds "Banana"; and so on. There is no risk of an ArrayIndexOutOfBoundsException because you never write an index expression at all.

SECTION 4

How It Works Under the Hood

When the Java compiler encounters an enhanced for loop, it translates it into one of two traditional patterns depending on whether the target is an array or a collection. Understanding this translation helps you predict the loop's behavior and know when to choose a different approach.

Translation for Arrays

When you write for (int n : numbers), the compiler generates code equivalent to a standard indexed loop. Here is what the compiler produces internally:

ARRAY TRANSLATION

for(inti=0;i<numbers.length;i++)intn=numbers[i];/∗body∗/for (int i = 0; i < numbers.length; i++) { int n = numbers[i]; /* body */ }

The compiler creates a hidden index variable i that increments from 0 to numbers.length − 1. On each iteration, the loop variable n is assigned numbers[i].

Translation for Collections

When the target implements the Iterable interface (like an ArrayList), the compiler uses an Iterator behind the scenes:

COLLECTION TRANSLATION

Iterator<T>it=collection.iterator();while(it.hasNext())Titem=it.next();/∗body∗/Iterator<T> it = collection.iterator(); while (it.hasNext()) { T item = it.next(); /* body */ }

The compiler obtains an Iterator from the collection, then calls hasNext() before each pass and next() to retrieve the current element.

⚠

Why Does This Matter?

Because the enhanced for loop uses an Iterator for collections, modifying the collection (adding or removing elements) inside the loop body will throw a ConcurrentModificationException. If you need to remove elements while iterating, use a traditional loop with Iterator.remove() instead.

SECTION 5

Common Syntax Patterns & Data Types

The enhanced for loop adapts to a wide variety of data types. The table below shows the most common patterns you will encounter in a typical Java course, along with an example snippet for each.

Data SourceDeclarationExample Snippet
int arrayfor (int n : nums)int[] nums = {1, 2, 3};
double arrayfor (double d : vals)double[] vals = {3.14, 2.72};
String arrayfor (String s : words)String[] words = {"hi", "bye"};
ArrayList<Integer>for (int n : list)ArrayList<Integer> list = new ArrayList<>();
HashSet<String>for (String s : set)HashSet<String> set = new HashSet<>();
Characters in a Stringfor (char c : str.toCharArray())String str = "Hello";

Common enhanced for loop patterns across data types

Traditional For Loop vs. Enhanced For LoopTraditional For LoopEnhanced For Loopint[] scores = {90, 85, 72};int sum = 0;for (int i = 0; i < scores.length; i++) { sum += scores[i];}int[] scores = {90, 85, 72};int sum = 0;for (int s : scores) { sum += s;}Lines of loop code:5Lines of loop code:3Risk of off-by-one error?YES — i <= vs i <Risk of off-by-one error?NO — automatic boundsAccess to index?YES — variable iAccess to index?NO — index hidden
Side-by-side comparison showing how the enhanced for loop reduces code volume and eliminates common indexing mistakes, while sacrificing direct access to the loop index.

The comparison diagram highlights the trade-off at the heart of choosing between loop styles. The enhanced for loop wins on readability and safety, but the traditional loop wins when you need the index value itself — for example, to replace an element at a specific position.

SECTION 6

Worked Example — Summing an ArrayList

Let's walk through a complete example: computing the average of a list of test scores stored in an ArrayList<Integer>.

Calculate the Average of Test Scores

  1. 1

    Step 1 — Declare and Populate the List

    Create an ArrayList<Integer> and add five scores: 88, 95, 73, 91, 68. Remember to import java.util.ArrayList at the top of your file.
    ArrayList<Integer> scores = new ArrayList<>(); with values 88, 95, 73, 91, 68 added via scores.add()
  2. 2

    Step 2 — Initialize a Sum Variable

    Declare an int sum = 0; before the loop. This accumulator will hold the running total as we iterate through each score.
    int sum = 0;
  3. 3

    Step 3 — Write the Enhanced For Loop

    Use the syntax for (int score : scores). On each iteration, score receives the next value from the list. Inside the body, add score to sum.
    for (int score : scores) { sum += score; }
  4. 4

    Step 4 — Compute the Average

    After the loop, divide sum by scores.size(). Since both are integers, cast to double for a decimal result: double avg = (double) sum / scores.size();
    sum = 88 + 95 + 73 + 91 + 68 = 415. Average = 415 ÷ 5 = 83.0
  5. 5

    Step 5 — Print the Result

    Use System.out.println("Average: " + avg); to display the output. The complete program is concise: just a few lines of setup, a one-line loop, and a calculation.
    Console output: Average: 83.0

SECTION 7

Strengths, Limitations & When to Choose

FeatureEnhanced For LoopTraditional For Loop
ReadabilityVery high — minimal syntaxModerate — more boilerplate
Off-by-one safetyImmune — no index expressionsVulnerable — easy to mistype boundary
Index accessNot availableFull access via loop variable
Modify collectionCannot safely add/removeCan add/remove with care
Traverse in reverseNot directly supportedEasily reversed with index decrement
Skip elementsCan use continue, but not skip by indexFull control with i += 2, etc.

Feature comparison: enhanced vs. traditional for loop

🔑

WHEN TO CHOOSE WHICH

Use the enhanced for loop as your default whenever you need to visit every element and you don't need the index. Switch to the traditional for loop only when you need to access the position, modify the collection in place, iterate in reverse, or skip elements by a specific step.

SECTION 8

Connection to Advanced Iteration

The enhanced for loop is your gateway to more advanced Java features. Once you're comfortable with it, you'll encounter two important evolutions: the Streams API and the forEach() method from Java 8.

AspectEnhanced For LoopStream.forEach()
Java version requiredJava 5+Java 8+
ParadigmImperative — step-by-stepFunctional — declarative pipeline
Can use break/continue?YesNo (use filter/takeWhile instead)
Chaining operationsRequires extra variables/loopsSupports map, filter, reduce in a single chain
Typical useSimple iteration, AP CS A examsData transformation, production code

Enhanced for loop vs. functional forEach in Java 8+

For AP Computer Science A, the enhanced for loop is one of the tested topics and is the recommended approach for traversing arrays and ArrayLists when the index is not needed. As you move to college-level Java courses, you'll find that the Streams API builds directly on the same iteration concepts — the idea of visiting each element and performing an action — but wraps them in a more powerful, composable framework.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Explain in your own words why the enhanced for loop cannot cause an ArrayIndexOutOfBoundsException. What mechanism prevents this error?
Show answer
The enhanced for loop does not expose an index variable to the programmer. Internally, the compiler generates the correct boundary check (using array.length for arrays or hasNext() for collections), so it is impossible for the index to go out of range. Because you never write the comparison expression yourself, there is no opportunity to accidentally use <= instead of <, which is the most common cause of off-by-one errors.

Question 2: BASIC CALCULATION

Given the array int[] vals = {4, 7, 2, 9, 5};, write an enhanced for loop that calculates and prints the sum of all elements. What value is printed?
Show answer
The loop would be: int sum = 0; for (int v : vals) { sum += v; } System.out.println(sum);. On each pass, the variable v takes the values 4, 7, 2, 9, and 5 in sequence. The running total progresses as 4 → 11 → 13 → 22 → 27. The printed value is 27.

Question 3: INTERMEDIATE

You have an ArrayList<String> containing {"cat", "elephant", "dog", "butterfly", "ox"}. Write an enhanced for loop that counts how many strings have more than 3 characters and prints that count.
Show answer
Declare int count = 0; before the loop, then write for (String s : list) { if (s.length() > 3) { count++; } }. Checking each word: "cat" has 3 characters (not counted), "elephant" has 8 (counted), "dog" has 3 (not counted), "butterfly" has 9 (counted), "ox" has 2 (not counted). The final count is 2. This problem combines the enhanced for loop with a conditional test and the String.length() method.

Question 4: APPLIED

A teacher stores student grades in ArrayList<Integer> grades containing {82, 94, 67, 88, 75, 91}. Using enhanced for loops only (no traditional loops), write code that: (a) finds the maximum grade, and (b) creates a new ArrayList<Integer> containing only grades of 80 or above.
Show answer
For part (a): Initialize int max = grades.get(0); then loop with for (int g : grades) { if (g > max) { max = g; } }. This yields max = 94. For part (b): Create ArrayList<Integer> honor = new ArrayList<>(); then loop with for (int g : grades) { if (g >= 80) { honor.add(g); } }. The resulting list contains {82, 94, 88, 91}. Note that we add to a new list — we never modify the original list during iteration, which avoids a ConcurrentModificationException.

Question 5: CRITICAL THINKING

A student writes the following code intending to double every value in an array: int[] nums = {1, 2, 3, 4}; for (int n : nums) { n = n * 2; } After the loop, what are the values in nums? Explain why, and then write correct code that actually doubles each element.
Show answer
The array remains {1, 2, 3, 4} — unchanged. The loop variable n is a copy of each element, not a reference to the element's position in the array. Reassigning n only changes the local copy; the original array entry is untouched. To actually modify the array, you must use a traditional for loop with index access: for (int i = 0; i < nums.length; i++) { nums[i] = nums[i] * 2; }. This is one of the most important limitations of the enhanced for loop — it provides read-only access to element values.

SUMMARY

Summary

Summary

The enhanced for loop (or for-each loop) uses the syntax for (Type item : collection) to iterate over every element in an array or any object implementing Iterable (such as ArrayList, HashSet, and LinkedList). It eliminates off-by-one errors by removing index management entirely, producing cleaner and safer code.

Under the hood, the compiler translates the loop into either an indexed loop (for arrays) or an Iterator-based loop (for collections). The loop variable is a copy of each element, so reassigning it does not modify the source. Use the enhanced for loop as your default for simple traversal; switch to a traditional for loop when you need index access, reverse iteration, or in-place modification.

Varsity Tutors • Java • Enhanced For Loop — Iterate collections with enhanced for loop