Card 03/ 09

ExampleDifficulty: Beginner1 min

Two Names for One Number, Which Is Not the Same Thing

The same two lines, on a number instead of a list. The shape of the code is identical and the result is the opposite.

java
int score = 10;

int sameScore = score;
sameScore = sameScore + 5;

System.out.println(score);
text
10

Line 3 copied what score held, and what it held was the number ten. sameScore now has its own ten, and adding five to it reaches nothing else. There are two numbers, and there always were.

Put this beside the basket and the rule comes out: assignment copies what the variable holds, and the only question is what that is. With a list it is an address, so both names reach one object. With an int it is the value, so there is nothing to share.

Neither case is an exception. Once you can say what a variable holds, you can predict the result without running it, which is most of what reading unfamiliar Java consists of.