AP® Computer Science A · Unit 3 · Topic 3.6
Passing an Object Reference into a Method
Java passes object references by value: the method gets a copy of the address, not the object. So calling a mutator through the parameter changes the real object, but reassigning the parameter itself does not touch the caller's variable.
A number parameter holds its own value, so changing it inside a method only changes a local copy. An object parameter holds something different: an address pointing to where the object actually lives on the heap. When you pass a Student into a method, Java copies that address into the parameter. Now two variables, the caller's and the parameter's, hold the same address. They are two names for one object.
That shared address explains both behaviors on this topic. If the method calls param.setName("New Name"), it follows the address to the real object and changes a field inside it. The caller's variable points at that same object, so it sees the new name too. But if the method does s = new Student("Other", 0), it only changes what the local copy of the address points at. The parameter now points somewhere new; the caller's variable never moves and still points at the original object.
This is the idea that makes constructors and mutator methods meaningful in class design: once an object exists, any reference to it can modify its state, which is why private fields and controlled setters matter. It also sets up later work with arrays and lists of objects, where the same rule applies to every element, and with aliasing, where two variables pointing at one object can cause changes to show up in a place you didn't expect.
Key terms
- reference
- The address of an object's location on the heap, stored in a variable.
- pass by value
- Java always copies the value stored in a variable into the parameter, whether that value is a number or an address.
- mutator method
- A method, like setName, that changes an object's fields rather than returning a new object.
- aliasing
- When two or more variables hold the same reference and so refer to one shared object.
Watch it explained
- How it worksHow does passing a reference copy the address and leave two names on one object?
- Worked exampleTrace a method that calls setName on a Student parameter and find the caller's object after.
- Worked exampleTrace a method that points its Student parameter at a new object and find what the caller sees.
- Common mistakeWhy doesn't reassigning a parameter inside a method change the caller's variable?
Check yourself
End of topic.