Card 04/ 10
All 10 cards
ConceptDifficulty: Intermediate1 min
Java Copies Everything You Pass, Including the Reference
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. Both are the same rule.
Java passes every argument by value. The method gets a copy of whatever the variable held, and the only question — again — is what it 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.