CoursesJVM internals for Kotlin and Android developers
Puzzle 2 · 3 of 5
Why do both names read eight?
Predict which changes survive a method call.
All puzzles in this course
The problem
A reference is a value that lets code reach an object. Two variables refer to the same bookmark counter. A helper receives one of them. Can it change what the other variable reads?
See it
Scroll sideways to see the full diagram.
The caller has a reference to a counter.
Step 1 of 4The second name reaches the same counter.
Step 2 of 4Writing through the parameter updates that object.
Step 3 of 4Reassigning the parameter leaves the caller pointing at the original.
Step 4 of 4
The building block
Each variable holds a reference. The call copies that value into the helper frame. Writing eight into the object changes the field visible through both names. Reassigning the helper parameter to a newly created counter changes only the local copy. Reverse the two statements in edit. Now the write lands on the new object and both caller variables still see seven. Compare the order of the field write and local store in the disassembly.
Call the original object A and the new one B. These letters label their identity so we can follow each object even when two objects happen to store the same number. A field belongs to an object. A parameter is a local name initialized when the call starts.
Counter first = new Counter(7);
Counter second = first;
edit(second);
| Operation inside the example | first | second | inside | Field values |
|---|---|---|---|---|
| Enter edit | A | A | A | A holds 7 |
| Write inside.value = 8 | A | A | A | A holds 8 |
| Assign inside = new Counter(99) | A | A | B | A holds 8, B holds 99 |
| Return to caller | A | A | helper finished | caller reads 8 twice |
Suppose the caller wants second to refer to B after the call. Have the helper return B, then assign that returned value to second in the caller. First continues to refer to A. This explains how one method can change a shared object's contents while replacing a caller's variable requires a separate assignment.
Try it
Optional local lab
Complete experiment 3 in the JVM source files. Record your prediction before running the program.
Check yourself
Sources
- Java language specification, method invocation — “assign the argument values to corresponding freshly created parameter variables”
What you now know
A copied reference can still point to the same object. Reassigning one local changes only that local.
Answer every question above correctly to unlock the next puzzle.
Something wrong or unclear on this page? Tell me: a puzzle that didn't click is a bug in the puzzle.