AP® Computer Science A glossary

Passing references

Also called: passing objects to methods

Course: AP® Computer Science A Shows up in: Unit 3: Class Creation

When an argument is an object reference, the parameter gets a copy of the reference, so both refer to the same object.

Appears in the course and exam description (CED): 3.6.A.13.6.A.2

Java always passes arguments by value; for an object the value copied is the reference, and no new object is created. Calling a mutator through the parameter changes the caller’s object, but assigning a new object to the parameter does not change the caller’s variable.

public class Box
{
    private int size;

    public Box(int s)
    {
        size = s;
    }

    public static void grow(Box b)
    {
        b.size++;            // changes the caller's object
        b = new Box(100);    // changes only the parameter
    }

    public static void main(String[] args)
    {
        Box mine = new Box(3);
        grow(mine);
        System.out.println(mine.size);
    }
}

Output:

4
Learn it properly, with a checkpoint 3.6 Methods: Passing and Returning References of an Object

Related terms

Was this page helpful?

No names are ever shown, and every public comment is checked by us first. Please do not include personal details. To get a reply, email [email protected].

↑ Top

Enlarged view of the selected figure