Let's go through it line by line.
Line 11
An easy start, no strings created here.
Line 12
We're assigning the String "Fred"
to s
. Although it looks like a String is created here, this string will live in the constant pool. The JVMS section 2.17.6 Creation of New Class Instances guarantees that the objects for string literals will at latest be created when the surrounding class is loaded, which by definition is before the method is invoked. So no new string objects are created on this line.
Line 13
The literal string "47"
is referenced, which again will have been created statically (as above). However there's also the invocation of the +
operator, which will create a new String in order to hold the result of the concatenation. So that's the first string created.
Line 14
The substring
method does indeed create a new String. It shares the underlying character array with its parent - and so takes up hardly any extra memory - but since Strings are immutable, each different string representation requires a different String
object. (This is probably a gotcha - my first instinctive response was "ah, string created by substring are special" but of course it still has to create a new object).
Line 15
As above - the uppercase representation is different, so a new String must be created to hold the result.
Line 16
Strings
override the toString()
method to simply return this
- hence no additional String is created.
The scores on the doors
By my count that's three String objects created during this method (with two of those objects sharing the same underlying character array, and with two pre-existing objects referenced for the string literals).