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

Review the reference exercise 4 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);

referenceTwo = new Coordinate2D(2, 2);

System.out.println(referenceOne);
System.out.println(referenceTwo);

Output

(1, 1)
(1, 1)
(1, 1)
(2, 2)

Step by step with memory diagrams

Step 1

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

System.out.println(referenceOne);
System.out.println(referenceTwo);

Memory diagram after Step 1

diagram showing referenceOne and referenceTwo pointing to the same box containing x and y, each with value 1

The first 2 lines are the same as in Reference exercise 2, so the memory diagram is the same.

Output after Step 1

(1, 1)
(1, 1)

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.

Step 2

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

System.out.println(referenceOne);
System.out.println(referenceTwo);

referenceTwo = new Coordinate2D(2, 2);

Memory diagram after Step 2

diagram showing referenceOne pointing to a box containing x with value 1 and y with value 1, and referenceTwo pointing to a different box containing x with value 2 and y with value 2

The right side of the last line, new Coordinate2D(2, 2);, makes a new object/instance of type Coordinate2D containing x: 2, y: 2.

The left side sets the value of referenceTwo to the memory address of the new object. In other words, it sets referenceTwo to point to the new object. The value of referenceTwo is the arrow pointing to the object.

The value of referenceOne remains unchanged.

Step 3

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

System.out.println(referenceOne);
System.out.println(referenceTwo);

referenceTwo = new Coordinate2D(2, 2);

System.out.println(referenceOne);
System.out.println(referenceTwo);

Memory diagram after Step 3

diagram showing referenceOne pointing to a box containing x with value 1 and y with value 1, and referenceTwo pointing to a different box containing x with value 2 and y with value 2

Output after Step 3

(1, 1)
(1, 1)
(1, 1)
(2, 2)

Additional classes & objects resources

Comments

Comment on Primitive types vs references exercises