Reference exercise 2 solution

Complete the Primitive types vs references exercises before reviewing the solutions.

Review the reference exercise 2 solution with AP CS Tutor Brandon Horn.

Original code

``````Coordinate2D referenceOne = new Coordinate2D(1, 1);
Coordinate2D referenceTwo = referenceOne;
System.out.println(referenceOne);
System.out.println(referenceTwo);
``````

Output

``````(1, 1)
(1, 1)
``````

Step by step with memory diagrams

Step 1

``````Coordinate2D referenceOne = new Coordinate2D(1, 1);
``````

Memory diagram after Step 1

This is the same first line as in Reference exercise 1, so the memory diagram is the same.

Step 2

``````Coordinate2D referenceOne = new Coordinate2D(1, 1);
Coordinate2D referenceTwo = referenceOne;
``````

Memory diagram after Step 2

On the 2nd line, the right side is evaluated first. The right side is `referenceOne`, which means the value of `referenceOne`. The value of `referenceOne` is the memory address of the object containing `x: 1, y: 1`. In the diagram, the value of `referenceOne` is the arrow.

The left side, `Coordinate2D referenceTwo`, makes a new variable/reference. The value of `referenceTwo` is set to a copy of the value of `referenceOne`.

`referenceOne` and `referenceTwo` point to the same object containing `x: 1, y: 1`.

Step 3

``````Coordinate2D referenceOne = new Coordinate2D(1, 1);
Coordinate2D referenceTwo = referenceOne;
System.out.println(referenceOne);
System.out.println(referenceTwo);
``````

Output after Step 3

``````(1, 1)
(1, 1)
``````

Both `print` statements print the same object, so the same output is produced twice. See Reference exercise 1 Step 3 for an explanation of what happens when `referenceOne` is printed.