String msg1, msg2, msg3;

msg1 = "Look Out!" ;

msg2 = "Look Out!" ;

msg3 = "Look Out!" ;

A good answer might be:

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. It would be useful to copy, paste, and run.

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):

Like 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 it saves space and time to have only one copy. Only rarely will you need to think about this difference. However: I've heard that the Sun Microsystems Java Certification Examination stresses this difference.

But the difference between == and equals() is very important, and you will be sunk if you are not careful with them.

QUESTION 21:

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

String str2 = "String Literal" ;    // small difference