The Null Object Reference


Referring to nothing

Remember that a variable holds a reference to an object. There are times when you want to say explicitly that a variable refers to nothing. For example, suppose that you have a sequence of objects to look at, where each object possesses a color and a size. Your goal is to find the largest of those objects that is blue. As you look through the sequence of objects, you would like to keep, in variable bestSoFar, a reference to the largest blue object that you have already seen. But, before you start the search, how to you initialize bestSoFar? You probably do not want to make it be the first object in the sequence, because that object might not be blue.

One way to handle that is to use the null object reference. Just say

  bestSoFar = null;
Making a variable hold null is not the same as storing nothing at all in it. The null reference is an explicit reference to nothing, and you can ask whether a variable holds it. For example, you can write
  if(bestSoFar == null)
  {
    ...
  }

Another common use of null is as an answer from a method where there is no suitable answer to produce. By returning null, the method is telling you that it could not find what you asked it to find. Some methods use that idea as an alternative to throwing an exception.


Only object references can be null

We have seen the distinction between primitive types and classes. The null object reference can only be used as the value of a variable whose type is a class. For example, you are not allowed to write

  int x = null;
because int is not a class. Variables with primitive types do not contain object references at all, so they cannot contain the special null object reference.


You cannot ask null to do anything

Special object reference null explicitly refers to no object. Since there is no object there, you cannot ask the nonexistent object to do something for you. Any time you do a dot operation on a variable that holds null, the program throws exception NullPointerException. For example, doing statements

  String x = null;
  int n = x.length();
causes the program to throw NullPointerException.