The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


null

When you create an object variable, remember that you are creating a reference to an object. Until you make the variable point to an object, the value of the variable is null. null is a special value in Java (and a Java keyword) that is used to mean "no object."

The declaration Point blank; is equivalent to this initialization

    Point blank = null;

and is shown in the following state diagram:

The value null is represented by a dot with no arrow.

If you try to use a null object, either by accessing an instance variable or invoking a method, you will get a NullPointerException. The system will print an error message and terminate the program.

    Point blank = null;
    int x = blank.x;              // NullPointerException
    blank.translate (50, 50);     // NullPointerException

On the other hand, it is legal to pass a null object as an argument or receive one as a return value. In fact, it is common to do so, for example to represent an empty set or indicate an error condition.



Last Update: 2011-01-24