Complete the Primitive types vs references exercises before reviewing the solutions.
Review the reference exercise 3 solution with AP CS Tutor Brandon Horn.
Original code
Coordinate2D referenceOne = new Coordinate2D(1, 1);
Coordinate2D referenceTwo = referenceOne;
referenceOne.setX(3);
referenceTwo.setY(4);
System.out.println(referenceOne);
System.out.println(referenceTwo);
Output
(3, 4)
(3, 4)
Step by step with memory diagrams
Step 1
Coordinate2D referenceOne = new Coordinate2D(1, 1);
Coordinate2D referenceTwo = referenceOne;
Memory diagram after Step 1
The first 2 lines are the same as in Reference exercise 2, so the memory diagram is the same.
Step 2
Coordinate2D referenceOne = new Coordinate2D(1, 1);
Coordinate2D referenceTwo = referenceOne;
referenceOne.setX(3);
Memory diagram after Step 2
referenceOne.setX(3)
(read referenceOne
dot setX 3
) means: go to the object to which referenceOne
points and run the setX
method with 3
. The setX
method changes the value of x
inside the object to 3
.
Running setX
does not change the value of referenceOne
or referenceTwo
. Running setX
changes the value of x
inside the object to which both referenceOne
and referenceTwo
point.
Step 3
Coordinate2D referenceOne = new Coordinate2D(1, 1);
Coordinate2D referenceTwo = referenceOne;
referenceOne.setX(3);
referenceTwo.setY(4);
Memory diagram after Step 3
The setY
method is run on the object to which referenceTwo
points. This is the same object to which referenceOne
points. The value of y
inside the object is changed to 4
. The values of referenceOne
and referenceTwo
, the memory address of that object, remain the same.
Step 4
Coordinate2D referenceOne = new Coordinate2D(1, 1);
Coordinate2D referenceTwo = referenceOne;
referenceOne.setX(3);
referenceTwo.setY(4);
System.out.println(referenceOne);
System.out.println(referenceTwo);
Memory diagram after Step 4
Output after Step 4
(3, 4)
(3, 4)
As in Reference exercise 2, both print
statements print the same object. See Reference exercise 1 Step 3 for an explanation of what happens when referenceOne
is printed.