1.6.13 Copying References vs Copying Values

Assignment Copies a Value

An assignment stores the value on the right in the variable on the left. The important question is what kind of value the variable holds.

Two int variables each hold 10 after value assignment.
Initial relationship
  • New
  • Changed
  • Removed
An int Variable Stores a Number

In this example, `secondScore` receives the number currently stored in `firstScore`:

int firstScore = 10;
int secondScore = firstScore;

The two variables now hold separate number values. Changing `secondScore` later does not change `firstScore`.

A Class Variable Stores a Reference

A Player variable holds a reference that leads to a Player object. The following assignment copies that reference:

Player secondPlayer = firstPlayer;

Both variables can now reach the same Player. No Player was created by this line.

Two Player variables both refer to the same Player object.
How the relationship changes
  • New
  • Changed
  • Removed
A Field Change Affects the Object

If `secondPlayer.Name` changes, `firstPlayer.Name` shows the same new value. The Name field belongs to the shared Player, not to either variable.

Variable Reassignment Changes One Path

If `secondPlayer` later receives a reference to a new Player, only that variable changes its destination. `firstPlayer` still reaches the original object.