go to previous page   go to home page   go to next page hear noise
String msg1, msg2, msg3;
msg1 = "Look Out!" ;
msg2 = "Look Out!" ;
msg3 = "Look Out!" ;

Answer:

Since these are identical string literals, only one object is created. The reference variables msg1, msg2, and msg3 all refer to the same object.


Example Program

Here is an example program that shows this subtle difference.

class LiteralEg
{
  public static void main ( String[] args )
  {
    String str1 = "String literal" ;  // create a literal
    String str2 = "String literal" ;  // str2 refers to the same literal
     
    String msgA = new String ("Look Out!");  // create an object
    String msgB = new String ("Look Out!");  // create another object
  
    if ( str1 == str2 ) 
      System.out.println( "This WILL print.");

    if ( msgA == msgB ) 
      System.out.println( "This will NOT print.");

  }

}

Here is a picture of the program (after the first four statements have run):

Literals

As with many optimizations, you almost wish they hadn't done it. It does confuse things. But real-world programs often use the same message in many places (for example "yes" and "no" and "hit enter") and it saves space and time to have only one copy. Only rarely will you need to think about this difference.

But the difference between == and equals() is very important, and you will be sunk if you don't know the difference.


QUESTION 24:

How would the program change if the second statement were changed to:

String str2 = "STRING LITERAL" ;    // small difference