Example Program

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

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 it saves space and time to have only one copy. Only rarely will you need to think about this difference. However: I've read 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 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