AP Computer Science A · Unit 3 lecture · Part 6 of 10 · 9 min

3.6 Passing and returning object referencesReferences: two names, one object

Mr. Thompkins
Here's a puzzle. I write Tank c = a; and then pour water out of c. Did a lose water too? If you can answer that with confidence, you've got the hardest idea in this unit.
?Wait, what does an object variable actually hold?
A variable of a class type holds a reference: think of it as an arrow that points to an object somewhere in memory. It does not hold the object itself. That's why it can be null, an arrow that points nowhere.

So when you assign one object variable to another, Java copies the arrow, not the object. After Tank c = a; there is still only one Tank, and two names for it. Programmers call c an alias of a. Anything you do through c, you do to the object a points at, because it's the same object.

1public class Tank2{3    private String name;4    private int liters;56    public Tank(String name, int liters)7    {8        this.name = name;9        this.liters = liters;10    }1112    public void add(int amount)13    {14        liters += amount;15    }1617    public void pourInto(Tank other, int amount)118    {19        liters -= amount;20        other.liters += amount;221    }2223    public Tank split(String newName)324    {25        int half = liters / 2;26        liters -= half;27        return new Tank(newName, half);328    }2930    public String getName() { return name; }31    public int getLiters() { return liters; }32}
  1. line 17 An object parameter: other refers to some other Tank
  2. line 20 Same class, so other.liters is allowed even though it is private
  3. line 23-27 Returns a reference to a brand new Tank
A Tank class. pourInto takes another Tank as a parameter, and split returns a new Tank.
1Tank a = new Tank("A", 50);2Tank b = new Tank("B", 10);3Tank c = a;14c.pourInto(b, 15);25Tank d = b.split("D");36System.out.println(a.getLiters() + " " + b.getLiters()7    + " " + c.getLiters() + " " + d.getLiters());8System.out.println(a == c);4
  1. line 3 No new: c is a second name for Tank A
  2. line 4 A loses 15 (35), B gains 15 (25)
  3. line 5 half = 25 / 2 = 12. B keeps 13, D gets 12
  4. line 8 == on objects asks: same object?
output › 35 13 35 12 true
Four variables, three objects. The new keyword appears three times, so three Tanks exist.
acbdTank A: 35 LTank B: 13 LTank D: 12 La and c point at one object4 variables, 3 objects
Memory after the client code runs. a and c are two arrows to the same Tank.
?Wait, what does == do with two objects?
For object variables, == asks whether both arrows point to the same object. a == c is true because they're aliases. Two different Tanks with the same name and liters would still give false. (For comparing Strings by their letters, you use equals, from Unit 1.)

Look closely at pourInto: it changes other.liters directly, even though liters is private. That's allowed. private means "only code inside the Tank class", not "only this object". A Tank method may read and change the private data of any Tank object it gets as a parameter.

Passing an object to a method

Java always passes arguments by copying them. For an object, what gets copied is the reference, so the parameter becomes one more alias of the caller's object. That gives two very different results. If the method calls a mutator through the parameter, the caller's object really changes. If the method assigns a new object to the parameter, only the method's copy of the arrow moves, and the caller never sees it.

1public static void topUp(Tank t)2{3    t.add(20);14}56public static void replace(Tank t)7{8    t = new Tank("New", 100);29}10// in main11Tank x = new Tank("X", 5);12topUp(x);13replace(x);14System.out.println(x.getName() + " " + x.getLiters());
  1. line 3 t refers to the same Tank as x, so this change is real
  2. line 8 Points the copy t somewhere new. x does not move
output › X 25
topUp changes the object. replace only re-aims its own parameter.
Pause and think
Why doesn't the output say New 100?
I thought about it. Show me
Inside replace, t = new Tank("New", 100); builds a new Tank and points the parameter t at it. The caller's variable x is a separate arrow that still points to Tank X. When replace ends, t and the new Tank are simply forgotten.

Because a method can change a mutable object passed to it, the course gives a good practice rule: don't change an object you were handed unless changing it is the method's job and the documentation says so. Callers trust that passing an object to a getter-like method leaves it alone.

Returning a reference

A method can also return an object. What comes back is a reference. split builds a new Tank and returns the arrow to it, and the caller stores that arrow in d. A method could just as well return a reference to an existing object, like a parameter it was given, or the current object itself, which you'll see with this in 3.9.

Trace with references
Trace the client code above (the Tank client with a, b, c and d) and explain each value printed.
  1. Tank a holds 50 liters and Tank b holds 10. c = a makes c a second name for Tank A. No new Tank.
    Why?
    No new, no new object. That's the quickest test for aliasing.
  2. c.pourInto(b, 15): the method runs on Tank A (c points there). A drops to 35, and other, which is b, rises to 25.
  3. b.split("D"): half is 25 / 2 = 12 with integer division. B keeps 25 - 12 = 13, and the method returns a new Tank D with 12.
  4. Print a, b, c and d: a and c are the same tank, so both show 35. Output: 35 13 35 12.
  5. a == c compares arrows: same object, so true.

Answer: 35 13 35 12, then true.

Stuck? Get a hint
  1. Count the news. Each one is one Tank.
  2. c and a share one Tank. Whatever happens to c happens to a.
  3. 25 / 2 is 12 in integer division. Which tank keeps the extra liter?
Check yourself
What is printed? (Use the Tank class above.)
Tank p = new Tank("P", 40);
Tank q = p;
q.add(5);
p = new Tank("R", 8);
System.out.println(p.getLiters() + " " + q.getLiters());
  1. A8 45
  2. B45 45
  3. C8 8
  4. D40 45
Show the answer

A. q = p makes q an alias, so q.add(5) changes the one Tank to 45. Then p = new Tank("R", 8) re-aims only p. q still points to the first Tank. The second choice is the top trap: assigning a new object to p doesn't drag q along.

  • Object variables hold references. Assigning one to another copies the reference and creates an alias.
  • A method that receives an object can change it through mutators, and the caller sees the change.
  • Assigning a new object to a parameter changes only the method's copy of the reference.
  • A method can use the private data of any object of its own class, such as other.liters.
  • Returning an object returns a reference. Don't change an object passed to you unless that's the method's job.