AP Computer Science A · Study guide

Reference Variables for Objects

AP® Computer Science A · Using Objects and Methods

Reference Variables for Objects

Declaring variables of the right reference type to hold objects, what the special value null means, how null differs from an empty string, and why calling a method through null stops a program.

Big Picture

To keep track of an object, a program stores a reference to it in a variable whose type is the object's class. A variable of a reference type holds an object reference or, if there is no object, the special value null. A null variable can be printed and compared, but any attempt to call a method through it fails with a NullPointerException, because there is no object for the method to act on.

1Variables That Hold Objects

A program cannot use an object it has no way to reach. Reference variables provide that way: Lamp desk = new Lamp(80); creates a lamp and stores a reference to it in desk, so later statements can write desk.getBrightness(). The variable must be declared with a type that can hold the object; a reference to a Lamp goes in a Lamp variable, and a reference to a String goes in a String variable.

Choosing the type is usually straightforward: use the class named after new, or String for a string literal. The compiler checks every assignment, so storing a reference of the wrong class in a variable is a compile-time error rather than a hidden bug. This check is one of the main benefits of declaring variable types.

A reference variable does not have to refer to an object right away. Programs often declare a variable before they know which object it should hold, for example a variable for "the best result so far" or "the file to read," and fill it in later. Until then, it can hold null.

Figure 1. Declare a reference variable with the class of the object it will hold. Only reference variables can hold null.

2The Value null

The keyword null is a special value that means "no object." A variable of a reference type holds an object reference or, if there is no object, null. It can be assigned directly, as in Lamp spare = null;, and compared with == and !=: spare == null is true exactly when spare refers to no object.

Printing a null reference displays the word null, and joining it to a string with + inserts the text "null". These operations are safe because they do not ask the missing object to do anything. Seeing "null" unexpectedly in output is a strong hint that a variable was never given an object.

Starting a variable at null is a deliberate choice that communicates "nothing here yet." It suits variables that will be filled in once some event happens: the most recent message received, the current file being processed, or the latest sighting in a log. The program must then make sure an object has been assigned before using the variable to call methods.

Figure 2. A variable of a reference type holds an object reference or, if there is no object, null.
Value in a reference variableMeaningCalling a method through it
A referenceThe variable refers to an objectRuns the method on that object
nullThere is no objectThrows a NullPointerException
Worked Example 1 Printing null

What null Looks Like in Output

Predict the output.

Code
String note = null;
System.out.println(note);
System.out.println("Note: " + note);
note = "Bring a jacket";
System.out.println("Note: " + note);
Output
null
Note: null
Note: Bring a jacket
  1. 1Printing a null reference displays the word null; no method is called on the missing object, so nothing goes wrong.
  2. 2Concatenation with a null reference also produces the text "null".
  3. 3After assignment, note refers to a real String object and its characters print.
Result: The output is null, Note: null, and Note: Bring a jacket. Printing or concatenating a null reference shows the word null.
Worked Example 2 Testing for null

Asking Whether a Variable Refers to an Object

Predict the output.

A small Lamp class and a short program
public class Lamp
{
    private int brightness;

    public Lamp(int b)
    {
        brightness = b;
    }

    public int getBrightness()
    {
        return brightness;
    }
}
Output
true
false
45
  1. 1spare == null is true at first: the variable holds no reference.
  2. 2After spare = new Lamp(45); the variable refers to an object, so the comparison is false.
  3. 3Now a method call is safe: spare.getBrightness() returns 45.
Result: The output is true, false, and 45. Comparing a reference with null using == tells you whether there is an object to use.
Worked Example 3 Declare now, assign later

A Variable That Starts Empty

A program records which bird was spotted most recently. Predict the output.

Code
String latest = null;
System.out.println(latest == null);
latest = "kestrel";
System.out.println(latest + " " + latest.length());
latest = "heron";
System.out.println(latest + " " + latest.length());
Output
true
kestrel 7
heron 5
  1. 1Start. Nothing has been spotted, so latest is null and the comparison prints true.
  2. 2First sighting. latest now refers to "kestrel", so calling length() is safe: 7.
  3. 3Second sighting. latest is reassigned to "heron": length 5. The "kestrel" object is no longer referred to by latest.
Result: The output is true, kestrel 7, and heron 5. Starting with null is a clear way to say "nothing yet," as long as methods are called only after an object has been assigned.

3Using a null Reference

Calling a method requires an object to call it on. When a reference variable holds null, there is no object, so a method call such as spare.getBrightness() cannot run. Java throws a NullPointerException, and unless the program handles it, the program stops at that statement.

The compiler cannot catch this problem, because a variable's value is only known when the program runs. Code that compiles perfectly can still fail with a NullPointerException if a variable is null at the moment a method is called through it. Before calling a method through a reference that might be null, make sure it has been given an object.

When the exception happens, Java prints its name along with the line number where it occurred. That line contains a method call through a null reference. The fix is rarely on that line itself: trace backward to find where the variable should have been given an object and was not, often a missing new or a variable that was reassigned to null earlier.

Worked Example 4 NullPointerException

Calling a Method Through null

What happens?

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

    public Lamp(int b)
    {
        brightness = b;
    }

    public int getBrightness()
    {
        return brightness;
    }
}
  1. 1The code compiles. spare is declared as a Lamp, and Lamp has getBrightness, so the compiler is satisfied.
  2. 2"before" prints.
  3. 3The method call fails at run time. There is no object for getBrightness to run on, so Java throws a NullPointerException and the program stops; "after" never prints.
Result: The program prints before, then stops with a NullPointerException. A reference must refer to an object before methods are called through it.
Common Mistake 1 · Calling a Method Before Creating the Object

Declaring Lamp spare; or Lamp spare = null; creates a variable, not a lamp. Calling spare.getBrightness() before assigning an object with new throws a NullPointerException. Create the object first.

4The Empty String Is Not null

The empty string, written "", is a genuine String object that contains zero characters. It has a length of 0, it can have methods called on it, and it is not equal to null. A null String variable, by contrast, refers to no object at all, so calling length() through it throws an exception.

The distinction matters whenever text may be missing. An empty string usually means "there is text, and it is blank," such as a form field left empty. null means "there is no text object yet." The two print differently, compare differently, and behave differently when methods are called.

Figure 3. The empty string "" is a String object with length 0. A null reference has no object to call methods on.
ExpressionString s = ""String s = null
s == nullfalsetrue
s.length()0NullPointerException
"[" + s + "]"[][null]
System.out.println(s)an empty linenull
Worked Example 5 Empty versus null

The Empty String Is a Real Object

Compare an empty string with a null reference.

An empty string
String a = "";
System.out.println(a.length());
System.out.println(a == null);
System.out.println("[" + a + "]");
Output
0
false
[]
A null reference
String b = null;
System.out.println("[" + b + "]");
System.out.println(b.length());
  1. 1The empty string. "" is a String object with no characters: its length is 0, it is not null, and it prints as nothing between the brackets.
  2. 2The null reference. Concatenation shows [null], but b.length() throws a NullPointerException because there is no object.
Result: The empty string prints 0, false, and []. The null reference prints [null] and then throws an exception. An empty string is something with nothing in it; null is the absence of any object.
Common Mistake 2 · Treating "" and null as the Same

"" is an object; null is the absence of one. "".length() is 0, but calling length() on a null reference throws a NullPointerException. Initialize string variables with "" when you plan to build text by joining onto them.

5Changing What a Variable Holds

A reference variable's value can change over time: it might start as null, later receive a reference to a new object, and later still be set back to null. Assigning null to a variable removes that variable's reference; it does not change or destroy the object. If another variable is an alias for the same object, the object remains fully usable through it.

When no variable refers to an object any longer, the program has no way to reach it, and it can never be used again. Java reclaims the memory of such unreachable objects automatically, so programmers do not delete objects themselves. Tracing which variables refer to which objects, as in the table below, shows exactly when an object becomes unreachable.

Figure 4. A reference variable can start as null, later refer to an object, and be set back to null. An object no variable refers to can no longer be used.
StatementabLamp object (80)
Lamp a = new Lamp(80);→ lamp(not declared)referred to by a
Lamp b = a;→ lamp→ lampreferred to by a and b
a = null;null→ lampreferred to by b
b = null;nullnullno references: unreachable
Worked Example 6 Removing a reference

Setting One Alias to null

Predict the output.

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

    public Lamp(int b)
    {
        brightness = b;
    }

    public int getBrightness()
    {
        return brightness;
    }
}
Output
true
80
  1. 1Lamp b = a; makes b an alias for the lamp.
  2. 2a = null; removes only a's reference. The object is unchanged, and b still refers to it.
  3. 3Results. a == null is true; b.getBrightness() still returns 80.
Result: The output is true and 80. Setting a variable to null affects only that variable; the object remains available through any other reference.
Common Mistake 3 · Thinking null Destroys the Object

a = null; changes only the variable a. If b refers to the same object, b still works exactly as before. An object becomes unusable only when no reference to it remains.

6Primitives Cannot Be null

null is a value for reference variables only. Primitive variables of type int, double, and boolean always hold an actual value, so int count = null; does not compile. If a program needs to represent "no number yet," it must choose a value with that meaning, such as 0 or −1, and document the choice.

This difference reflects what each kind of variable stores. A primitive variable holds the value itself, and every bit pattern is some number or true/false. A reference variable holds a way to find an object, and null is the one reference that leads nowhere.

The same reasoning explains default behavior in larger programs. A missing number is a design decision that needs a sentinel value, while a missing object can be represented directly with null. Both approaches need clear documentation so that every programmer using the variable knows what its "empty" state looks like.

Worked Example 7 Primitives and null

Why an int Cannot Be null

Explain the compile error.

Code that does not compile
int count = null;
System.out.println(count);
  1. 1null is a reference value. It means "no object" and can only be stored in a variable of a reference type.
  2. 2int is a primitive type. An int variable always holds a number; there is no object to be missing.
  3. 3Fix. Give the variable a number, such as int count = 0;.
Result: The compiler reports incompatible types: null cannot be converted to int. Only reference variables can hold null.
Common Mistake 4 · Comparing a Primitive With null

Because primitives can never be null, an expression such as count == null with an int variable does not compile. Checks against null make sense only for reference variables.

Four Habits for Reference Variables

1. Match the Class

Declare the variable with the class of the object it will hold.

2. null Means No Object

Printing it shows null; calling methods through it fails.

3. "" Is Not null

The empty string is a real object with length 0.

4. Only References

Primitive variables can never hold null.

Core Synthesis

A variable of a reference type holds an object reference or, if there is no object, null. Reference variables must be declared with a type that matches the objects they will hold. A null reference can be printed, concatenated, and compared with ==, but a method call through it results in a NullPointerException. The empty string is a real object, while null means there is no object, and primitive variables can never be null.