Card 04/ 10
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.
| You pass | The method receives | It can change |
|---|---|---|
An int | A copy of the number | Nothing the caller can see |
A List | A copy of the address | The list at that address |
A List, then reassigns the parameter | A copy of the address | Nothing the caller can see |
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.
← → move through sections and cards