Skip to main content
Engineering LibreTexts

1.7: The null Keyword

  • Page ID
    19649
  • When you create an object variable, remember that you are storing a reference to an object. In Java, the keyword null is a special value that means “no object”. You can declare and initialize object variables this way:

    Point blank = null;
    

    The value null is represented in state diagrams by a small box with no arrow, as in Figure 10.7.1.

    State diagram showing a variable that contains a null reference.
    Figure \(\PageIndex{1}\): State diagram showing a variable that contains a null reference.

    If you try to use a null value, either by accessing an attribute or invoking a method, Java throws a NullPointerException.

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

    On the other hand, it is legal to pass a null reference as an argument or receive one as a return value. For example, null is often used to represent a special condition or indicate an error.

    • Was this article helpful?