Unit 4 Cycle 2 Day 1: Array Aliasing Trap
Share
Array Aliasing Trap
Section 4.1 — Array Creation and Access
Key Concept
Array aliasing occurs when two variables reference the same array object. After int[] b = a, both a and b point to the same array in memory. Modifying b[0] also changes a[0] because they share the same data. This is different from copying: int[] b = Arrays.copyOf(a, a.length) creates an independent copy. The AP exam tests this by asking what happens to one variable's array after modifications through the other variable.
Consider the following code segment.
What is printed?
Answer: (B) 99
b = a copies the reference, not the array. Both a and b point to the same array. Changing b[0] also changes a[0].
Why Not the Others?
(A) 0 would be the default, but b[0]=99 modifies the shared array.
(C) No error. Both references are valid.
(D) Assignment of array references is valid.
Common Mistake
Arrays are objects. b = a creates an alias, not a copy. Both variables reference the SAME array in memory.
AP Exam Tip
Array assignment copies the reference, not the contents. To copy, use a loop. This aliasing trap appears frequently on the AP exam.