Unit 4 Cycle 1 Day 6: Enhanced For Cannot Modify Array

Unit 4 Foundation (Cycle 1) Day 6 of 28 Foundation

Enhanced For Cannot Modify Array

Section 4.2 — Traversing Arrays

Key Concept

The enhanced for loop cannot modify array elements because the loop variable holds a copy of each value, not a reference to the array slot. Assigning to the loop variable only changes the local copy. To modify an array, you must use an indexed for loop and assign directly to arr[i]. However, for arrays of objects, the enhanced for loop can modify the objects' state through method calls because the loop variable is a copy of the reference, which still points to the same object.

Consider the following code segment.

int[] nums = {1, 2, 3, 4, 5}; for (int n : nums) { n = n * 2; } System.out.println(nums[0] + " " + nums[4]);

What is printed?

Answer: (B) 1 5

The enhanced for loop variable n is a copy of each element. Assigning n = n * 2 modifies the copy, not the original array. The array is unchanged: nums[0]=1, nums[4]=5.

Why Not the Others?

(A) The array elements are not modified. Only the loop variable copy changes.

(C) Neither element is modified.

(D) Neither element is modified.

Common Mistake

The enhanced for loop variable is a COPY of the array element. Modifying the loop variable does NOT change the array. Use a standard for loop with arr[i] = ... to modify elements.

AP Exam Tip

To modify array elements, use for (int i = 0; i < arr.length; i++) { arr[i] = ...; }. Enhanced for loops cannot modify the array.

Review this topic: Section 4.2 — Traversing Arrays • Unit 4 Study Guide
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.