AP Computer Science A · Study guide

Passing and Returning Object References

AP® Computer Science A · Class Creation

Passing and Returning Object References

What happens when objects are passed to and returned from methods: parameters receive copies of references, so methods can change mutable objects; reassigning a parameter changes nothing outside; returned references can expose private state; and private access works class by class.

Big Picture

When an argument is an object reference, the parameter is initialized with a copy of that reference; it does not create a new independent copy of the object. If the parameter refers to a mutable object, the method can use the reference to alter the object's state, so it is good practice not to modify mutable parameters unless the specification requires it. When a return expression evaluates to an object reference, the reference itself is returned, not a copy. And methods cannot access the private data and methods of a parameter unless the parameter is the same type as the method's enclosing class.

1Reference Parameters

Java passes every argument by value, but for objects the value being copied is a reference. When an argument is an object reference, the parameter is initialized with a copy of that reference; it does not create a new independent copy of the object. After the call begins, the caller's variable and the method's parameter are two arrows pointing at one object.

This is efficient, since an object of any size is passed by copying one reference, and it has a direct consequence: anything the method does to the object through its parameter is visible to the caller. Anything the method does to the parameter variable itself, such as reassigning it, is not.

Figure 1. When an argument is an object reference, the parameter is initialized with a copy of that reference; it does not create a new independent copy of the object.
Inside the methodEffect on the caller's objectEffect on the caller's variable
Call a mutator through the parameter (p.moveBy(1, 1))ChangedStill refers to the same object
Reassign the parameter (p = new Point(0, 0))UnchangedUnchanged
Call only accessors (p.getX())UnchangedUnchanged

2Changing a Mutable Argument

A mutable object is one whose state can change after it is created, such as a Point with a moveBy method. If the parameter refers to a mutable object, the method or constructor can use this reference to alter the state of the object. A method that calls p.moveBy(1, 1) moves the caller's point.

Sometimes that is exactly the intent, for example a method whose documented job is to adjust an object. But it is good programming practice to not modify mutable objects that are passed as parameters unless required in the specification. Unexpected changes to a caller's object are a classic source of bugs, because nothing at the call site suggests the object might change.

Worked Example 1 Mutating through a parameter

A Method That Moves the Caller's Point

Predict the output.

The Point class, a Tools class, and a short program
public class Point
{
    private int x;
    private int y;

    public Point(int x0, int y0)
    {
        x = x0;
        y = y0;
    }

    public int getX()
    {
        return x;
    }

    public int getY()
    {
        return y;
    }

    public void moveBy(int dx, int dy)
    {
        x = x + dx;
        y = y + dy;
    }

    public String show()
    {
        return "(" + x + ", " + y + ")";
    }

    public int manhattanTo(Point other)
    {
        return Math.abs(x - other.x) + Math.abs(y - other.y);
    }
}

public class Tools
{
    public static void nudge(Point p)
    {
        p.moveBy(1, 1);
    }
}
Output
(4, 5)
  1. 1The call copies the reference. p and spot refer to the same Point (Figure 1).
  2. 2p.moveBy(1, 1) changes that one object.
  3. 3The caller sees the change, because spot still refers to the same object.
Result: The output is (4, 5). When a parameter refers to a mutable object, the method can use the reference to alter the state of the caller's object.
Worked Example 2 Good practice

Reading a Parameter Without Changing It

This method needs only to read its parameter, so it does not modify it. Predict the output.

The Point class, a Tools class, and a short program
public class Point
{
    private int x;
    private int y;

    public Point(int x0, int y0)
    {
        x = x0;
        y = y0;
    }

    public int getX()
    {
        return x;
    }

    public int getY()
    {
        return y;
    }

    public void moveBy(int dx, int dy)
    {
        x = x + dx;
        y = y + dy;
    }

    public String show()
    {
        return "(" + x + ", " + y + ")";
    }

    public int manhattanTo(Point other)
    {
        return Math.abs(x - other.x) + Math.abs(y - other.y);
    }
}

public class Tools
{
    public static String quadrantLabel(Point p)
    {
        if (p.getX() >= 0 && p.getY() >= 0)
        {
            return "first quadrant";
        }
        return "elsewhere";
    }
}
Output
first quadrant
(6, 8)
  1. 1Accessors only. The method calls getX and getY, never a method that changes the point.
  2. 2The caller's object is unchanged: (6, 8).
Result: The output is first quadrant, then (6, 8). It is good programming practice not to modify mutable objects passed as parameters unless the specification requires it.
Common Mistake 1 · Assuming a Method Cannot Change Your Object

A method that receives a reference to a mutable object can change that object. Check the method's documentation, or its code, before assuming your object will be the same after the call.

3Reassigning a Parameter

Assigning a new reference to a parameter, as in p = new Point(0, 0);, changes only the method's own copy of the reference. The parameter now refers to a different object, but the caller's variable still refers to the original object, which was not modified at all.

The distinction between using the arrow (calling a method through it) and redirecting the arrow (assigning to the parameter) explains every case. Strings fall into the second group automatically: since a String cannot be changed, every "change" to a string parameter is really a reassignment, and the caller's string is never affected.

Figure 2. A method can alter a mutable object through a parameter, but reassigning the parameter only changes the method's own copy of the reference.
Worked Example 3 Reassigning a parameter

Pointing the Parameter Somewhere Else

Predict the output.

The Point class, a Tools class, and a short program
public class Point
{
    private int x;
    private int y;

    public Point(int x0, int y0)
    {
        x = x0;
        y = y0;
    }

    public int getX()
    {
        return x;
    }

    public int getY()
    {
        return y;
    }

    public void moveBy(int dx, int dy)
    {
        x = x + dx;
        y = y + dy;
    }

    public String show()
    {
        return "(" + x + ", " + y + ")";
    }

    public int manhattanTo(Point other)
    {
        return Math.abs(x - other.x) + Math.abs(y - other.y);
    }
}

public class Tools
{
    public static void reset(Point p)
    {
        p = new Point(0, 0);
    }
}
Output
(3, 4)
  1. 1p = new Point(0, 0) makes the parameter refer to a new object.
  2. 2The caller's variable is untouched: spot still refers to the original (3, 4), which was never modified (Figure 2).
Result: The output is (3, 4). A method can change the object a parameter refers to, but reassigning the parameter itself never affects the caller's variable.
Worked Example 4 Immutable parameters

A String Parameter Cannot Be Changed

Predict the output.

Code
public static void excite(String s)
{
    s = s + "!";
    System.out.println("inside: " + s);
}
Output
inside: hello!
outside: hello
  1. 1s + "!" builds a new String, and the assignment points s at it.
  2. 2The original string cannot be changed, and word still refers to it.
Result: The output is inside: hello! and outside: hello. Because strings are immutable, passing a String to a method can never change the caller's text.
Common Mistake 2 · Trying to Replace the Caller's Object

A method cannot make the caller's variable refer to a different object by assigning to its parameter. If a method needs to provide a new object, it should return the new object, and the caller should assign the result.

4Returning References

When the return expression evaluates to an object reference, the reference is returned, not a reference to a new copy of the object. An accessor that returns a reference to a private mutable instance variable therefore gives the caller an alias of the object's internal state; the caller can then change the object without calling any of its mutators.

To keep private state private, an accessor can return a copy of a mutable object instead, built with the same data. Returning primitives and strings never has this problem: primitives are returned as copies of their values, and strings cannot be changed.

Figure 3. When the return expression evaluates to an object reference, the reference is returned, not a reference to a new copy of the object.
Accessor returnsCaller receivesCan the caller change the object's state?
A primitive (int, double, boolean)A copy of the valueNo
A StringA reference to an immutable objectNo
A reference to a private mutable objectAn alias of the private objectYes: state is exposed
A new copy of that objectA separate objectNo
Worked Example 5 Returning references

An Accessor That Leaks Private State

Compare two versions of getLocation.

Returning the reference
public class Point
{
    private int x;
    private int y;

    public Point(int x0, int y0)
    {
        x = x0;
        y = y0;
    }

    public int getX()
    {
        return x;
    }

    public int getY()
    {
        return y;
    }

    public void moveBy(int dx, int dy)
    {
        x = x + dx;
        y = y + dy;
    }

    public String show()
    {
        return "(" + x + ", " + y + ")";
    }

    public int manhattanTo(Point other)
    {
        return Math.abs(x - other.x) + Math.abs(y - other.y);
    }
}

public class Marker
{
    private Point location;

    public Marker(int x, int y)
    {
        location = new Point(x, y);
    }

    public Point getLocation()
    {
        return location;
    }
}
Output
(7, 7)
Returning a copy
public class Point
{
    private int x;
    private int y;

    public Point(int x0, int y0)
    {
        x = x0;
        y = y0;
    }

    public int getX()
    {
        return x;
    }

    public int getY()
    {
        return y;
    }

    public void moveBy(int dx, int dy)
    {
        x = x + dx;
        y = y + dy;
    }

    public String show()
    {
        return "(" + x + ", " + y + ")";
    }

    public int manhattanTo(Point other)
    {
        return Math.abs(x - other.x) + Math.abs(y - other.y);
    }
}

public class Marker
{
    private Point location;

    public Marker(int x, int y)
    {
        location = new Point(x, y);
    }

    public Point getLocation()
    {
        return new Point(location.getX(), location.getY());
    }
}
Output
(2, 2)
  1. 1First version. return location; returns the reference to the marker's own private Point. The caller's loc becomes an alias, and loc.moveBy moves the marker: (7, 7).
  2. 2Second version. The accessor returns a new Point with the same coordinates. Moving the copy leaves the marker at (2, 2).
Result: The first version prints (7, 7) and the second prints (2, 2). When a method returns an object reference, the reference is returned, not a copy; returning a copy keeps private mutable state private.
Common Mistake 3 · Returning a Private Mutable Object Directly

return location; hands out a reference to the object's internal Point. Code that changes the returned point changes the marker, bypassing encapsulation. Return a copy when callers should only read the value.

5Private Access and Parameters

Methods cannot access the private data and methods of a parameter that holds a reference to an object unless the parameter is the same type as the method's enclosing class. Inside the Point class, a method with a parameter Point other may read other.x directly, because privacy in Java is per class, not per object.

For parameters of any other class, a method must use that class's public methods, exactly as any outside code would. This rule lets objects of the same class cooperate efficiently, as when comparing coordinates or copying data, while still keeping each class's internals hidden from all other classes.

Figure 4. Methods cannot access the private data and methods of a parameter unless the parameter is the same type as the method's enclosing class.
Code locationExpressionAllowed?
Method inside Point, parameter Point otherother.xYes
Method inside Point, parameter Marker mA private field of mNo
Any method in Mainp.xNo
Anywherep.getX()Yes (public)
Worked Example 6 Same-class access

Reading Another Point's Private Coordinates

manhattanTo reads other.x and other.y directly. Predict the output, then explain why the second program does not compile.

Inside the Point class: allowed
public class Point
{
    private int x;
    private int y;

    public Point(int x0, int y0)
    {
        x = x0;
        y = y0;
    }

    public int getX()
    {
        return x;
    }

    public int getY()
    {
        return y;
    }

    public void moveBy(int dx, int dy)
    {
        x = x + dx;
        y = y + dy;
    }

    public String show()
    {
        return "(" + x + ", " + y + ")";
    }

    public int manhattanTo(Point other)
    {
        return Math.abs(x - other.x) + Math.abs(y - other.y);
    }
}
Output
7
Inside another class: not allowed
public class Point
{
    private int x;
    private int y;

    public Point(int x0, int y0)
    {
        x = x0;
        y = y0;
    }

    public int getX()
    {
        return x;
    }

    public int getY()
    {
        return y;
    }

    public void moveBy(int dx, int dy)
    {
        x = x + dx;
        y = y + dy;
    }

    public String show()
    {
        return "(" + x + ", " + y + ")";
    }

    public int manhattanTo(Point other)
    {
        return Math.abs(x - other.x) + Math.abs(y - other.y);
    }
}
  1. 1Distance. |1 − 4| + |2 − 6| = 3 + 4 = 7.
  2. 2Why other.x is allowed. manhattanTo is written inside Point, and other is also a Point; private access is granted to the whole class.
  3. 3Why a.x fails in Main. Main is a different class, so x is off limits there.
Result: The first program prints 7; the second does not compile. A method can access the private data of a parameter only when the parameter is the same type as the method's enclosing class.
Common Mistake 4 · Reading Private Fields of a Different Class

Inside Marker, a Point parameter's x is off limits even though the code is inside a class; it is the wrong class. Use p.getX().

6Good Practice With References

Three habits prevent most reference surprises. Do not modify mutable parameters unless the method's documented purpose is to do so. When storing a mutable object received from outside, or returning one held inside, use a copy if the two sides should stay independent. And when reading code, ask of each method call whether it might change an object that other variables also refer to.

These habits are the practical side of encapsulation. An object stays in control of its own state only if no outside code holds a reference to its mutable internals, and callers can trust their own objects only if the methods they call change those objects deliberately and visibly.

Four Habits for References in Methods

1. Same Object, Two Arrows

A reference parameter shares the caller's object.

2. Use the Arrow, Not Redirect It

Mutating shows outside; reassigning does not.

3. Copy Mutable Internals Out

Returned references are aliases.

4. Private Is Per Class

Same-class parameters may use private members.

Core Synthesis

When an argument is an object reference, the parameter is initialized with a copy of that reference; it does not create a new independent copy of the object. If the parameter refers to a mutable object, the method or constructor can use this reference to alter the state of the object, and it is good programming practice to not modify mutable objects passed as parameters unless required in the specification. When the return expression evaluates to an object reference, the reference is returned, not a reference to a new copy of the object. Methods cannot access the private data and methods of a parameter that holds a reference to an object unless the parameter is the same type as the method's enclosing class.