Topic 3.6 — Methods: Passing and Returning References of an Object
Goal: understand how object references are passed to methods and returned from methods, and how aliasing can cause changes through one reference to be seen through another.
The big idea
In Java, variables that hold objects store a reference (think: an address), not the whole object.
When you pass an object to a method, the method receives a copy of the reference — so both variables can end up pointing to the same object.
Primitive vs reference (quick compare)
| Type | What the variable stores | Example |
|---|---|---|
| Primitive | the actual value | int x = 5; |
| Reference | a reference to an object | String s = "hi"; |
Passing a reference into a method
The parameter gets a copy of the reference (not a copy of the whole object).
public static void addExclamation(StringBuilder sb) {
sb.append("!");
}
StringBuilder msg = new StringBuilder("Hi");
addExclamation(msg);
// msg is now "Hi!"
msgandsbrefer to the same object.- So changes through
sbaffect whatmsgsees.
Aliasing (two names, one object)
If two variables reference the same object, that’s called aliasing.
int[] a = {1, 2, 3};
int[] b = a; // b aliases a
b[0] = 99;
System.out.println(a[0]); // 99
You didn’t “copy the array” — you copied the reference.
Returning a reference
A method can return a reference to an object. The caller then holds a reference too.
public static int[] makeOnes(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = 1;
return arr; // returns a reference
}
int[] x = makeOnes(4); // x references the returned array
Important: “pass-by-value” in Java
Java is always pass-by-value… but for objects, the “value” being copied is the reference.
public static void changeRef(int[] arr) {
arr = new int[]{7, 7, 7}; // changes parameter's reference only
}
int[] nums = {1, 2, 3};
changeRef(nums);
// nums is still {1, 2, 3}
- Reassigning
arrdoes not changenums. - But modifying
arr[0]would change the original array.
How to avoid surprise aliasing
- Be careful when you do
b = afor arrays/objects. - If you truly need a copy, you must create a new object and copy the values.
- On AP, many questions test whether you recognize aliasing effects.
Quick self-check
- When you pass an object into a method, what gets copied?
- What is aliasing?
- If
b = afor arrays, did you copy the array? - What’s the difference between modifying an object vs reassigning a reference?
- Predict: if two variables reference the same array, what happens when you change one element?