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.
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.
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.
null.| Value in a reference variable | Meaning | Calling a method through it |
|---|---|---|
| A reference | The variable refers to an object | Runs the method on that object |
null | There is no object | Throws a NullPointerException |
What null Looks Like in Output
Predict the output.
String note = null;
System.out.println(note);
System.out.println("Note: " + note);
note = "Bring a jacket";
System.out.println("Note: " + note);
null
Note: null
Note: Bring a jacket
- 1Printing a null reference displays the word
null; no method is called on the missing object, so nothing goes wrong. - 2Concatenation with a null reference also produces the text "null".
- 3After assignment,
noterefers to a realStringobject and its characters print.
null.Asking Whether a Variable Refers to an Object
Predict the output.
public class Lamp
{
private int brightness;
public Lamp(int b)
{
brightness = b;
}
public int getBrightness()
{
return brightness;
}
}
true
false
45
- 1
spare == nullistrueat first: the variable holds no reference. - 2After
spare = new Lamp(45);the variable refers to an object, so the comparison isfalse. - 3Now a method call is safe:
spare.getBrightness()returns 45.
null using == tells you whether there is an object to use.A Variable That Starts Empty
A program records which bird was spotted most recently. Predict the output.
String latest = null;
System.out.println(latest == null);
latest = "kestrel";
System.out.println(latest + " " + latest.length());
latest = "heron";
System.out.println(latest + " " + latest.length());
true
kestrel 7
heron 5
- 1Start. Nothing has been spotted, so
latestisnulland the comparison printstrue. - 2First sighting.
latestnow refers to "kestrel", so callinglength()is safe: 7. - 3Second sighting.
latestis reassigned to "heron": length 5. The "kestrel" object is no longer referred to bylatest.
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.
Calling a Method Through null
What happens?
public class Lamp
{
private int brightness;
public Lamp(int b)
{
brightness = b;
}
public int getBrightness()
{
return brightness;
}
}
- 1The code compiles.
spareis declared as aLamp, andLamphasgetBrightness, so the compiler is satisfied. - 2"before" prints.
- 3The method call fails at run time. There is no object for
getBrightnessto run on, so Java throws aNullPointerExceptionand the program stops; "after" never prints.
before, then stops with a NullPointerException. A reference must refer to an object before methods are called through it.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.
"" is a String object with length 0. A null reference has no object to call methods on.| Expression | String s = "" | String s = null |
|---|---|---|
s == null | false | true |
s.length() | 0 | NullPointerException |
"[" + s + "]" | [] | [null] |
System.out.println(s) | an empty line | null |
The Empty String Is a Real Object
Compare an empty string with a null reference.
String a = "";
System.out.println(a.length());
System.out.println(a == null);
System.out.println("[" + a + "]");
0
false
[]
String b = null;
System.out.println("[" + b + "]");
System.out.println(b.length());
- 1The empty string.
""is aStringobject with no characters: its length is 0, it is notnull, and it prints as nothing between the brackets. - 2The null reference. Concatenation shows
[null], butb.length()throws aNullPointerExceptionbecause there is no object.
null is the absence of any object."" 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.
null, later refer to an object, and be set back to null. An object no variable refers to can no longer be used.| Statement | a | b | Lamp object (80) |
|---|---|---|---|
| Lamp a = new Lamp(80); | → lamp | (not declared) | referred to by a |
| Lamp b = a; | → lamp | → lamp | referred to by a and b |
| a = null; | null | → lamp | referred to by b |
| b = null; | null | null | no references: unreachable |
Setting One Alias to null
Predict the output.
public class Lamp
{
private int brightness;
public Lamp(int b)
{
brightness = b;
}
public int getBrightness()
{
return brightness;
}
}
true
80
- 1
Lamp b = a;makesban alias for the lamp. - 2
a = null;removes onlya's reference. The object is unchanged, andbstill refers to it. - 3Results.
a == nullistrue;b.getBrightness()still returns 80.
null affects only that variable; the object remains available through any other reference.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.
Why an int Cannot Be null
Explain the compile error.
int count = null;
System.out.println(count);
- 1
nullis a reference value. It means "no object" and can only be stored in a variable of a reference type. - 2
intis a primitive type. Anintvariable always holds a number; there is no object to be missing. - 3Fix. Give the variable a number, such as
int count = 0;.
null cannot be converted to int. Only reference variables can hold 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.
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.