Strings and Object References in Java

The String class is used for text manipulation. As you read, you will learn different ways to create Strings, methods to manipulate Strings, the String concatenation operator '+', and about how Strings are immutable.

5. Null Assigned to any Reference Variable


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 .