AP Computer Science A · Study guide

Reference Type Variables

AP® Computer Science A · Using Objects and Methods

Reference Type Variables

What a variable of a class type actually stores: a reference to an object rather than the object itself, and what that means for assignment, aliases, reassignment, and comparing with ==.

Big Picture

Java has two kinds of types. Variables of the primitive types, int, double, and boolean, store their values directly. Every class defines a reference type, and a variable of a reference type holds an object reference, which can be thought of as the memory address of that object. The object itself lives elsewhere in memory. This difference explains why copying a reference variable makes two variables refer to the same object, and why == on references asks "same object?" rather than "same values?"

1Two Kinds of Variables

A primitive variable is a box that holds a value: int count = 7; puts 7 in the box named count. A reference variable is a box that holds a reference, a way of locating an object. String city = "Lisbon"; creates a String object containing "Lisbon" somewhere in memory and puts a reference to it in city.

Objects can be large: a string can hold thousands of characters, and an object can contain many attributes. Storing a compact reference in the variable, instead of a copy of the whole object, lets Java pass objects around efficiently. The cost is that you must keep track of which variables refer to which objects, since several variables can refer to the same one.

Figure 1. A primitive variable stores its value. A variable of a reference type holds an object reference, which can be thought of as the memory address of that object.
Primitive variableReference variable
Typesint, double, booleanAny class: String, Scanner, Lamp
What the variable storesThe value itselfA reference to an object (like a memory address)
Effect of y = x;Copies the value; the variables stay independentCopies the reference; both refer to the same object
Meaning of ==Same valueSame object
Worked Example 1 Classifying types

Primitive or Reference?

For each declaration, decide whether the variable is a primitive type or a reference type, and what it stores.

  1. double price = 4.25;
  2. String code = "B7";
  3. boolean open = true;
  4. Lamp desk = new Lamp("green", 80);
  5. Scanner input;
  1. 11 and 3. double and boolean are primitive types; the variables store 4.25 and true directly.
  2. 22. String is a class, so code is a reference variable holding a reference to a String object containing "B7".
  3. 34. Lamp is a class; desk holds a reference to the newly created Lamp object.
  4. 45. Scanner is a class, so input is a reference variable. It has been declared but not yet given an object.
Result: Variables of the primitive types store values; variables whose type is a class store references. Any type whose name is a class, including String, is a reference type.

2Declaring Reference Variables

A reference variable is declared like any other variable: the type, then the name. The type is a class name: String name;, Lamp desk;, Scanner input;. The declared type determines which objects the variable can refer to; a Lamp variable can hold a reference to a Lamp object but not to a String.

Declaration and object creation are separate steps that are often written together. Lamp desk = new Lamp("green", 80); declares the variable desk on the left, creates a new Lamp object on the right, and stores the reference to that object in desk. Strings are a special case: a string literal such as "Lisbon" creates a String object without writing new.

DeclarationVariable typeCan refer to
String name;StringString objects
Lamp desk;LampLamp objects
Scanner input;ScannerScanner objects
int total;int (primitive)Holds an int value directly, not a reference
Worked Example 2 Declared types

The Reference Must Match the Declared Type

Explain why this does not compile.

Code that does not compile
public class Lamp
{
    private String color;
    private int brightness;

    public Lamp(String c, int b)
    {
        color = c;
        brightness = b;
    }

    public void dim()
    {
        brightness = brightness - 10;
    }

    public int getBrightness()
    {
        return brightness;
    }
}
  1. 1Declared type. porch is declared as a Lamp, so it can hold only a reference to a Lamp object.
  2. 2The value. "red" is a String object, which is not a Lamp.
  3. 3Fix. Create a lamp and store its reference: Lamp porch = new Lamp("red", 60);.
Result: The compiler reports incompatible types: a String cannot be converted to a Lamp. A reference variable's type determines which objects it can refer to.
Common Mistake 1 · Thinking the Variable Is the Object

The variable desk is not the lamp; it refers to the lamp. This distinction matters whenever references are copied or reassigned. A helpful habit is to draw reference variables as boxes containing arrows, and objects as separate boxes the arrows point to.

3References as Memory Addresses

A variable of a reference type holds an object reference, which can be thought of as the memory address of that object. An address does not contain the house; it tells you where to find it. When code calls desk.dim(), Java follows the reference stored in desk to the object and runs dim on that object.

Java never shows you the actual address, and you never need it. What matters is the consequence: two variables holding the same reference lead to the same object, exactly as two people holding the same address arrive at the same house. Thinking of references as addresses makes the behavior of assignment, aliases, and == predictable.

The same picture explains method calls with object arguments. When a reference variable is passed to a method, the parameter receives a copy of the reference, so the method can reach the very same object. Primitive arguments, by contrast, give the method a copy of the value, and nothing the method does to its parameter can affect the caller's variable. Both cases follow one rule, call by value; what differs is whether the value being copied is a number or a reference.

Figure 2. With primitives, assignment copies the value itself, so the two variables remain independent.
Worked Example 3 Primitives copy values

The Same Steps With int Variables

Compare with the previous example. Predict the output.

Code
int x = 5;
int y = x;
y = y - 3;
System.out.println(x);
System.out.println(y);
Output
5
2
  1. 1int y = x; copies the value 5 into y.
  2. 2y = y - 3; changes only y, to 2.
  3. 3x is unaffected and still holds 5 (Figure 2).
Result: The output is 5 and 2. Assigning primitives copies values; assigning references copies references, which is why the Lamp example behaved differently.

4Aliases: Two Variables, One Object

Assigning one reference variable to another copies the reference, not the object. After Lamp b = a;, the variables a and b hold the same reference, so they refer to the same object. Two references to the same object are called aliases. Any change made to the object through one alias is visible through the other, because there is only one object to change.

Aliasing is often useful, for example when a method receives a reference to an object it should update. It can also cause surprises when a programmer expects Lamp b = a; to make a copy. To get a separate object with the same values, you must create a new object with new.

Figure 3. Assigning one reference variable to another copies the reference, not the object. Both variables then refer to the same object.
Worked Example 4 Aliases

Two Variables, One Object

Predict the output.

The Lamp class and a short program
public class Lamp
{
    private String color;
    private int brightness;

    public Lamp(String c, int b)
    {
        color = c;
        brightness = b;
    }

    public void dim()
    {
        brightness = brightness - 10;
    }

    public int getBrightness()
    {
        return brightness;
    }
}
Output
70
70
  1. 1One object is created. Only one new appears, so there is only one Lamp.
  2. 2Lamp b = a; copies the reference in a into b. Both refer to the same object (Figure 3).
  3. 3b.dim() changes that object's brightness to 70.
  4. 4Both variables report 70, because both refer to the one object that was dimmed.
Result: Both lines print 70. When two reference variables hold the same reference, they are aliases: a change made through one is visible through the other.
Common Mistake 2 · Expecting Assignment to Copy an Object

Lamp b = a; does not create a second lamp. It creates a second reference to the same lamp. Only new creates a new object. Count the new expressions to count the objects.

5Reassigning a Reference Variable

A reference variable can be given a different reference at any time. a = new Lamp("red", 40); creates a new object and stores its reference in a. Any other variable that referred to the old object, such as an alias b, still refers to the old object; reassigning a changes where a points, nothing else.

Tracing such code is easiest with a table that records which object each variable refers to after every statement. Update a variable's column only when it appears on the left side of an assignment, and update an object's attributes when a method is called through any variable that refers to it.

Figure 4. Assigning a new object to a reference variable changes only that variable. Any alias keeps referring to the original object.
Statementa refers tob refers to
Lamp a = new Lamp("white", 80);white lamp (80)(not declared)
Lamp b = a;white lamp (80)white lamp (80)
a = new Lamp("red", 40);red lamp (40)white lamp (80)
a.dim();red lamp (30)white lamp (80)
Worked Example 5 Reassignment

Pointing a Variable at a New Object

Predict the output.

Using the same Lamp class
public class Lamp
{
    private String color;
    private int brightness;

    public Lamp(String c, int b)
    {
        color = c;
        brightness = b;
    }

    public void dim()
    {
        brightness = brightness - 10;
    }

    public int getBrightness()
    {
        return brightness;
    }
}
Output
30
80
  1. 1First two lines. a and b both refer to the white lamp.
  2. 2a = new Lamp("red", 40); creates a second object and stores its reference in a. b still refers to the white lamp (Figure 4).
  3. 3a.dim() dims the red lamp: 40 → 30.
  4. 4b still refers to the white lamp, which was never dimmed: 80.
Result: The output is 30 and 80. Reassigning a reference variable changes which object it refers to; it does not change the object it used to refer to.
Worked Example 6 Strings and references

Reassigning a String Variable

String variables are reference variables too. Predict the output.

Code
String s = "tide";
String t = s;
s = s + "s";
System.out.println(s);
System.out.println(t);
Output
tides
tide
  1. 1String t = s; makes t an alias of the String object "tide".
  2. 2s = s + "s"; builds a brand-new String object, "tides", and stores its reference in s. The original object is not modified.
  3. 3t still refers to the original "tide".
Result: The output is tides, then tide. Joining strings creates a new object and reassigns the variable, so an alias of the old string is unaffected, exactly like reassigning a Lamp variable.
Common Mistake 3 · Thinking Reassignment Changes the Old Object

After a = new Lamp("red", 40);, the white lamp that a used to refer to is unchanged. Reassignment moves the arrow; it does not modify, copy, or delete the object the arrow used to point to.

6Comparing References With ==

For primitive variables, == compares values. For reference variables, == compares the references themselves: it is true only when both variables refer to the same object. Two separately created objects with identical attribute values are still different objects, so == reports false.

To ask whether two objects hold equal data, a class provides a method for that purpose. For strings, that method is equals: first.equals(second) compares the characters, while first == second only asks whether they are the same object. Using == to compare string contents is a classic mistake.

The two comparisons answer different questions, and both are useful. == answers "are these two variables aliases?", which matters when you need to know whether a change through one will be seen through the other. equals answers "do these objects represent the same value?", which is what most comparisons of strings need.

Worked Example 7 Comparing references

Same Object or Just Equal Values?

The operator == on reference variables compares the references, that is, whether both variables refer to the same object. Predict each result.

Using the same Lamp class
public class Lamp
{
    private String color;
    private int brightness;

    public Lamp(String c, int b)
    {
        color = c;
        brightness = b;
    }

    public void dim()
    {
        brightness = brightness - 10;
    }

    public int getBrightness()
    {
        return brightness;
    }
}
Output
false
true
  1. 1a == b. Two separate new calls create two objects. Their attribute values match, but they are different objects, so the references differ: false.
  2. 2a == c. c was assigned a's reference, so both refer to the same object: true.
Result: The results are false and true. == asks whether two references point to the same object, not whether two objects hold equal data.
Common Mistake 4 · Using == to Compare Object Contents

== on references tests identity (same object), not equality of contents. Two lamps with the same color and brightness are not == unless they are the same object. For strings, use equals to compare characters.

Four Habits for Reference Variables

1. Draw Arrows

A reference variable holds an arrow to an object, not the object.

2. Count the news

Each new creates one object; assignment never does.

3. Aliases Share Changes

Two variables with the same reference see the same object.

4. == Means Same Object

Use equals to compare string contents.

Core Synthesis

A variable of a reference type holds an object reference, which can be thought of as the memory address of that object. Assigning one reference variable to another copies the reference, so both variables refer to the same object and changes made through either are visible through both. Reassigning a reference variable changes only which object that variable refers to. The == operator on references tests whether two variables refer to the same object, while primitive variables store and compare their values directly.