Card 04/ 10

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.

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.