APrep Open the app

AP Computer Science A · Unit 4: Data Collections

4.3 Enhanced for Loop for Arrays

What is an enhanced for loop?

The enhanced for loop (for-each loop) traverses every element of an array without needing an index variable. Syntax: `for (DataType var : array)`. On each iteration, `var` holds the next element's value, in order from index 0 to the last index. It's great for reading elements but cannot modify the original array elements.

When to use it — and when not to

Use the enhanced for loop when you just need to read/process each element in order and don't need the index. Avoid it when you need to modify array elements, access multiple arrays by matching index, traverse backward, or skip/repeat elements — a traditional indexed for loop is required for those tasks.

Common pitfalls

Assigning a new value to the loop variable (e.g., `var = var * 2;`) does not change the array — `var` is just a copy of the element's value. Also, you cannot access the index inside an enhanced for loop, so tasks needing `arr[i]` explicitly require a standard for loop instead.

Key terms

Enhanced for loop syntax
for (DataType var : array) { ... } — iterates through each element of the array in order.
Why use an enhanced for loop?
It simplifies code for reading/processing every element of an array without needing an index variable.
Limitation of enhanced for loops
Cannot modify array elements or access the index — the loop variable is a copy of each value.
When to use a regular for loop instead
When you need to modify elements, know the index, traverse backward, or process multiple arrays by matching index.
Order of traversal in enhanced for loop
Always goes sequentially from the first element (index 0) to the last element in the array.

Try an AP-style question

Code

int[] a = {1, 2, 3};
for (int x : a)
    x = x * 10;
System.out.print(a[0]);

What is printed?

  1. An error
  2. 10
  3. 1
  4. 0
Show the answer

C. x is a copy; the array is unchanged.

Practice 8 AP-style questions with instant explanations, flashcards and spaced review.

Study 4.3 free in APrep