Card 01/ 09

ConceptDifficulty: Beginner1 min

What a Variable Holds, and Why That Is Two Answers

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.

Java has two kinds of variable and the difference is not what they are for. It is what the variable physically holds.

What each kind of variable holds
KindThe variable holdsWritten as
PrimitiveThe value itselfint, double, boolean, and five more
ReferenceThe address of an object stored elsewhereEvery type 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.

A primitive variable holds a value; a reference variable holds an address

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. Almost every Java surprise about identity starts here.