Null Assigned to any Reference Variable

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Can null be assigned to reference variables of any type?

Answer:

Yes.

Null Assigned to any Reference Variable

It would be awful if each class had its own special value to show that no object of that class was present. We need a universal value that means "nothing here". The value null works for this and can be assigned to any reference variable.

In most programs, objects come and objects go, depending on the data and on what is being computed. (Think of a computer game, where monsters show up, and monsters get killed). A reference variable sometimes does and sometimes does not refer to an object, and can refer to different objects at different times. 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.

Inspect the code below. Variables a and c are initialized to object references. Variable b is initialized to null.

class NullDemo1
{
  public static void main (String[] arg)
  {
    String a = "Random Jottings";
    String b = null;
    String c = "";

    if ( a != null ) 
      System.out.println( a );

    if ( b != null ) 
      System.out.println( b );

    if ( c != null ) 
      System.out.println( c );
  }
}    

QUESTION 5:

What exactly is variable c initialized to? Click here for a .