AP® Computer Science A · Unit 1 · Topic 1.13
Object Creation with new, and Aliasing
When you assign one object variable to another, you copy the reference, not the object. Both variables now point at the same thing on the heap, so a change through one shows up through the other.
The new keyword builds an object out on the heap and gives you back its address, a reference. That reference is what actually lives in your variable — not the object itself. An int or double variable holds its value directly, but an object variable holds a pointer to where the real data sits. This is why object variables behave so differently from primitive ones.
When you write b = a for two array or object variables, Java copies the reference, not the array or object it points to. After that line, a and b are two separate names for the exact same thing on the heap. There is no second object anywhere. Change the object through b, using b[0] = 99 for example, and that change is visible through a too, because a was never a separate array — it was always this one, now sitting with a 99 in slot zero.
This is called aliasing, and it is the single most important mental model for the rest of the course. Method calls that pass objects as arguments hand over a copy of the reference the same way, which is why a method can reach into an object and mutate it permanently, but cannot make the caller's variable point somewhere new. The one exception that trips people up is immutable objects like String: operations such as concatenation never change the original object, they build a new one and only the reassigned variable points at it, so aliasing has no visible effect.
Key terms
- heap
- The region of memory where every object created with new actually lives.
- reference
- The address of an object on the heap, stored inside an object variable.
- aliasing
- When two or more variables hold references to the same object, so changes through one are visible through the other.
- immutable
- Describes an object, like a String, whose internal state can never be changed after it is created.
Watch it explained
- How it worksHow does new build an object out on the heap and hand back a reference to it?
- How it worksWalk me through two variables pointing at one object while one of them changes it.
- Worked exampleTrace int[] a = {1,2,3}; int[] b = a; b[0] = 99; and find what printing a[0] gives afterwards.
- Common mistakeWhy doesn't assigning one array variable to another make an independent copy?
- Going furtherWhat changes when the object that two variables share is immutable, like a String?
Check yourself
End of topic.