Card 03/ 09
Primitive Assignment Example: Two Names for Two Numbers
Copy an int into a second variable, change the copy, and the original stays 10.
Assigning one primitive variable to another copies the value, so the two are independent from then on. The same two lines as copying a list variable and adding to the copy, on a number instead of a list:
int score = 10;
int sameScore = score;
sameScore = sameScore + 5;
System.out.println(score);10Line 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 List<String> sameBasket = basket; sameBasket.add("bread");, where adding through the copy changes the original list, 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.
← → move through sections and cards