go to previous page   go to home page   go to next page        
String c = "";

Answer:

empty string

The code "" calls for a literal, which is a String object. Although the object exists, it contains no characters (since there are no characters inside "").

The reference variable c is initialized to a reference to this String object. This is most certainly a different value than null.

The Empty String

A String object that contains no characters is still an object. Such an object is called an empty string. It is similar to having a blank sheet of paper, versus having no paper at all. Overlooking this distinction is one of the classic confusions of computer programming. It will happen to you. It still happens to me. To prepare for future confusion, study this program, step-by-step:

class NullDemo1
{
  public static void main (String[] arg)
  {
    String a = "Random Jottings";   // 1.  an object is created; 
                                    //     variable a refers to it
    String b = null;                // 2.  variable b refers to no object.
    String c = "";                  // 3.  an object is created 
                                    //     (containing no characters); 
                                    //     variable c refers to it

    if ( a != null )                // 4.  ( a != null ) is true, so
       System.out.println( a );     // 5.  println( a ) executes.
                                              
    if ( b != null )                // 6.  ( b != null ) is false, so
       System.out.println( b );     // 7.  println( b ) is skipped.

    if ( c != null )                // 8.  ( c != null ) is true, so
       System.out.println( c );     // 9.  println( c ) executes.
                                    //     (but it has no characters to print.) 
  }
}    

The System.out.println() method expects a reference to a String object as a parameter. The example program tests that each variable contains a String reference before calling println() with it. (If println() gets a null parameter, it prints out "null" which would be OK. But some methods crash if they get a null parameter. Usually you should ensure that methods get the data they expect.)

QUESTION 6:

Examine the following code snippet:

String alpha = new String("Red Rose") ;

alpha = null;

. . .
  1. Where is an object constructed?
  2. What becomes of that object?