The bytecode for:
String name = new String("Joe");
is located between locations 0 and 9. When these bytecodes are executed, they create two String objects (at location 0 and 4 *).
We will now examine the bytecode produced to construct the String parameter for the PrintStream [ Note 1 ] println method :
name + " is my name."
The bytecode that is executed for this statement is between addresses 13 and 29.
Strings are immutable [ Note 2 ] and therefore a StringBuffer object is required to perform the concatenation. This StringBuffer object is created when the bytecode at location 13 is executed (thus far we have created three objects: two Strings and one StringBuffer).
Another String object is created at location 24 (thus bringing the number of created objects to 4). The append method is used to concatenate the Strings (the first append at position 21 appends name to the newly created zero length StringBuffer, the second append at position 26 appends " is my name." to the same StringBuffer). Another String object is created at location 29. The toString method invokes the constructor on String that takes a StringBuffer as a parameter and returns the newly created String. The total number of objects created is now five for this simple piece of code.
0 new #203 dup 4 ldc #21 6 invokespecial #22 9 astore_1 10 getstatic #8 13 new #5 16 dup 17 invokespecial #23 20 aload_1 21 invokevirtual #24 24 ldc #25 26 invokevirtual #24 29 invokevirtual #26 32 invokevirtual #10