Skip to main content
Lesson 12 - Object References
Lesson MenuPreviousNext
  
The null Value page 9 of 10

  1. In most programs, objects are created and objects are destroyed, depending on the data and on what is being computed. A reference variable sometimes does and sometimes does not refer to an object. You need a way to say that a variable does not now refer to an object. You do this by assigning null to the variable.

  2. The value null is a special value that means "no object." A reference variable is set to null when it is not referring to any object.

    public class nullDemo
    {
      public static void main (String[] args)
      {
        String a =                // 1. an object is created; 
            new String("stringy") //    variable a refers to it
        String b = null;          // 2. variable b refers to no
                                  //    object.
        String c =                // 3. an object is created 
            new String("");       //    (containing no chars)
                                  //     variable c refers to it
        if (a != null)            // 4. statement true, so 
           System.out.println(a); //    the println(a) executes.
                                                  
        if (b != null)            // 5. statement false, so the
           System.out.println(b); //    println(b) is skipped.
    
        if (c != null)            // 6. statement true, so the
           System.out.println(c); //    println(c) executes (but
                                  //    it has no characters to 
                                  //    print).
      }
    }    
    Run Output:
    
    stringy
  3. Variables a and c are initialized to object references. Variable b is initialized to null. Note that variable c is initialized to a reference to a String object containing no characters. Therefore println(c) executes, but it has no characters to print. Having no characters is different from the value being null.


Lesson MenuPreviousNext
Contact
 ©ICT 2003, All Rights Reserved.