The Stacks
UNIT 4: DATA COLLECTIONS · TOPIC 4.4

4.4 Array Traversals

Visiting every element. The standard for loop gives you the index; the enhanced for loop gives you the element. Know when each is appropriate.

What you need to know

  • Standard traversal: for (int i = 0; i < arr.length; i++) with arr[i]. Use when you need the index — to modify elements, compare neighbors, or traverse backward or partially.
  • Enhanced for (for-each): for (int x : arr) — x takes each element's value in order. Cleaner when you only read elements.
  • In an enhanced for loop, assigning to the loop variable does not change the array — x is a copy of the element (for primitives). For objects, x is a copy of the reference, so calling mutators on it does affect the object in the array.
  • Enhanced for can't skip elements, go backward, or access the index.
  • Backward: for (int i = arr.length - 1; i >= 0; i--).
  • Loop bound i <= arr.length is the classic out-of-bounds bug.

Worked example

int[] nums = {2, 4, 6};

for (int n : nums)            // enhanced: read only
{
    n = n * 10;               // does NOT change nums
}
// nums still {2, 4, 6}

for (int i = 0; i < nums.length; i++)   // standard: can modify
{
    nums[i] = nums[i] * 10;
}
// nums now {20, 40, 60}

Trace it yourself

Step through with the buttons, or use the ← → keys. Changed variables are highlighted.

Exam tip: If the question modifies the array through the loop variable of an enhanced for loop, the array is unchanged — that's the trick. If it calls a mutator method on an object element, the object is changed. Index needed? Standard loop.

Going deeper

The nuance, edge cases, and connections that turn a 3 into a 5.

  • Standard for loop: index available, can go any direction, any step, can modify elements, can compare neighbors (arr[i] and arr[i + 1]), can stop early. It's the general tool.
  • Enhanced for: for (type x : arr) — x takes each element's value in order. No index. Cleaner for read-only traversal. The type must match the element type (or a compatible one).
  • The enhanced-for copy rule: for primitives, x is a copy — assigning to x doesn't touch the array. For objects, x is a copy of the reference — x.setValue(5) modifies the object in the array, but x = new Thing() doesn't replace the array element. Same as 3.6.
  • Backward traversal must be a standard loop: for (int i = arr.length - 1; i >= 0; i--). Note >= 0 to include index 0.
  • Partial traversals: every other element (i += 2), first half (i < arr.length / 2), skipping the first (i = 1). All need the standard loop.
  • Bounds: i < arr.length is right. i <= arr.length throws on the last iteration. Comparing neighbors: i < arr.length - 1.
  • Nested traversal (comparing every pair): outer i over all, inner j from i + 1 to end. That's n(n−1)/2 comparisons.

Mistakes that cost points

  • Modifying the enhanced-for variable and expecting the array to change. Primitives: no change. Objects: only via mutators.
  • <= length. Exception on the last pass.
  • Backward loop with > 0. Skips index 0.
  • Using enhanced for when you need the index. Switch to standard.

Practice questions

Written in the style of the real exam. Try each one before revealing the answer.

Q1 What is printed by the following code?
int[] a = {1, 2, 3};
for (int v : a)
{
    v += 10;
}
System.out.println(a[0] + a[1] + a[2]);
  1. A 6
  2. B 36
  3. C 16
  4. D A compile-time error
Show answer

Answer: A. v is a copy; modifying it leaves the array unchanged. 1 + 2 + 3 = 6.

Q2 Which of the following correctly prints the elements of arr in reverse order?
  1. A for (int i = arr.length; i > 0; i--) System.out.println(arr[i]);
  2. B for (int i = arr.length - 1; i >= 0; i--) System.out.println(arr[i]);
  3. C for (int x : arr) System.out.println(x);
  4. D for (int i = arr.length - 1; i > 0; i--) System.out.println(arr[i]);
Show answer

Answer: B. Start at length - 1, go down to and including 0. A starts out of bounds; D skips index 0.

Key vocabulary

Traversal
visiting every element of an array
Enhanced for loop
for (type x : arr) — iterates over elements without an index