Card 01/ 09
Primitive and Reference Variables: What a Variable Holds
Copy one variable into another and change the copy: sometimes the original changes too.
A Java variable holds one of two things. A primitive variable, such as an int, holds the value itself. A reference variable, such as a List or a String, holds the address of an object stored elsewhere in memory. What the variable holds decides what happens when you copy it.
You copy one variable into another, change the copy, and the original changes with it. You do the same thing an hour later with different variables, and the original sits there untouched. Nothing in the two lines looks different; what differs is the kind of variable.
| Kind | The variable holds | Written as |
|---|---|---|
| Primitive | The value itself | int, double, boolean, and five more, all lower case |
| Reference | The address of an object stored elsewhere | Every class type, such as String or List, which by convention start with a capital letter |
Assignment always does the same thing: it copies what the variable holds. For an int that is the number, so you end up with two independent numbers. For a List that is an address, so you end up with two variables pointing at one list.
The diagram shows the difference. The int variable is the value; the List variable is an arrow to a list that lives somewhere else, and copying the variable copies the arrow.
That single rule is why a method can change your list and cannot change your counter, and why two objects that look identical can still fail a comparison with ==. Almost every Java surprise about identity starts here.
← → move through sections and cards