Methods: Passing &
Returning References
Understand how Java handles object references when passed to and returned from methods, and why aliasing matters.
What Is a Reference?
In Java, variables that hold objects don't store the object itself. Instead, they store a reference: a pointer to the object's location in memory. Think of it as an address that tells Java where the actual data lives on the heap.
Primitives vs References
Why Does This Matter?
Understanding reference passing is critical because it determines whether a method can permanently change the data your program works with. Getting this wrong leads to subtle bugs that are hard to track down.
The Core Rule
What Can the Method Do?
Mutation vs Reassignment
| Mutation | Reassignment | |
|---|---|---|
| Action | p.setAge(10) | p = new Dog() |
| What changes? | The object's internal state | The parameter's local pointer |
| Caller sees it? | Yes | No |
| Why? | Same object, same heap address | Local copy now points elsewhere |
Two collaborators work on one shared model
Two variables can provide access to one shared object. Copying a reference creates another access path; it does not duplicate the object.Mutation and parameter reassignment
Java passes every argument by value. A copied reference initially reaches the same object, so its mutation is shared. Reassigning the parameter to a new object leaves the caller’s reference pointing to the original object.Returning References
A method can return a reference to an object. The caller receives a reference to the same object on the heap: no copy of the object is made.
Understanding Aliasing
How to Trace Reference Passing
Example 1: Mutation Through a Reference
Example 2: Reassignment Doesn't Escape
Example 3: Mixed Operations
The null Reference
A reference variable can hold the special value null, meaning it points to no object. Calling any method on a null reference throws a NullPointerException at runtime.
Common Mistakes
Summary Table
| Scenario | Caller Affected? | Reason |
|---|---|---|
| p.setField(val) | Yes | Mutates shared object |
| p = new Obj() | No | Reassigns local copy |
| p = null | No | Reassigns local copy |
| return p | Yes (if captured) | Caller receives a reference |
| p.getList().add(x) | Yes | Mutates nested object |
Question 1 of 5
Consider the following code. What is printed?
Question 2 of 5
What does a.getName() return after this code runs?
Question 3 of 5
What is printed by this code?
Question 4 of 5
After this code runs, what does b.getName() return?
Question 5 of 5
What is printed?