StringTest.java

Download this source file

// StringTest - Test your understanding of Strings.
// What is the output of this program?
// Written 2/2001 by Wayne Pollock, Tampa Florida USA.
// (Part 1 Suggested by a netnews posting in comp.lang.java.programmer
// by Igor Shafran on 2/20/01.)

class StringTest
{
   public static void main ( String [] args )
   {
      // Part 1:
      String A = null;
      String B = " String";
      System.out.println( A + B );

      // Part 2:
      String s1 = "abc";
      String s2 = new String( "abc" );

      if ( s1 == s2 )
         System.out.println( "s1 == s2" );
      else
         System.out.println( "s1 != s2" );

      if ( s1 == "abc" )
         System.out.println( "s1 == \"abc\"" );
      else
         System.out.println( "s1 != \"abc\"" );
   }
}

See the Answer






























Answer

Part 1:

(Adopted from a posting on 2/21/01 in comp.lang.java.programmer by Matthew Denner):

When in doubt about what some method is actually doing you can print the .class file in a readable (more or less) way with

   javap -c -private StringTest | more

Examing the results reveals what is actually being done in the compiled code is more like this:

   String A = null;
   String B = " String";
   StringBuffer buffer = new StringBuffer();
   buffer.append( A );
   buffer.append( B );
   System.out.println( buffer.toString() );

You'll find that the call to buffer.append( A ) puts a String which says "null" into buffer.  The compiler will do this for you as a "feature".  The StringBuffer.append( String ) method checks to see if the String being appended is null.  If it is then it appends the value of String.valueOf( null ).  If it isn't null than it appends the characters of the String one at a time.  In general it's better practice to try not to add (concatinate) Strings but to use StringBuffers directly.

The code for String.valueOf(Object) will check for null and if it is then it will return the string "null".  This is why you see "null String" instead of having a NullPointerException at runtime.

Part 2:

Since Strings are immutable (i.e., read-only, constant, final), Java builds a pool of all the different String literals used in the program, but only one copy of each.  All String references to the same literal are equal, since they refer to the same String object.

Since s1 and s2 are different objects, the program will print s1 != s2.  However since s1 refers to the single "abc" String literal, the program correctly prints s1 == "abc".


Send comments and questions to pollock@acm.org.
Valid HTML 4.01!   Valid CSS!   CAST: Bobby WorldWide Approved 508   CAST: Bobby WorldWide Approved AAA