Card 04/ 10

ConceptDifficulty: Intermediate1 min

Pass-by-Value in Java, Including References

A method adds to your list and you see it; it adds to your number and you do not. It is one rule.

Java passes every argument by value: the method receives a copy of whatever the caller's variable held. For a number that is the number. For an object it is the object's address, so the method can change the object at that address but can never change the caller's variable.

You pass a list to a method, the method adds to it, and the caller sees the addition. You pass a number to a method, the method adds to it, and the caller sees nothing. The question, as with assignment, is what the variable held.

What the method receives, and what it can therefore affect
You passThe method receivesIt can change
An intA copy of the numberNothing the caller can see
A ListA copy of the addressThe list at that address
A List, then reassigns the parameterA copy of the addressNothing the caller can see
A method's parameter is a second variable holding a copy of the same address

Both arrows point at one list, so following either arrow reaches the same object. Overwriting the second arrow leaves the first one exactly where it was, which is why reassigning a parameter is invisible to the caller.

So "can this method change my object?" has a mechanical answer: it can change the object, and it can never change your variable. Nothing a method does to its own parameters reaches the names you used at the call.