Answer: The result of this code fragment is "spring winter spring summer". There are two reference variables, s1 and s2. There are a total of eight String objects created as follows: "spring", "summer " (lost), "spring summer", "fall" (lost), "spring fall" (lost), "spring summer spring" (lost), "winter" (lost), "spring water" (at this point only "spring" is lost). Only two of the eight String objects are not lost in this process.
There are some errors and some unclarities in this answer.
First, the answer states the String objects "spring", "spring summer", "fall", "spring fall", "spring summer spring", "winter", "spring winter" are created. These objects do not exist, because they _all_ have a trailing space. Only "summer " is correct in the answer. The printed string "spring winter spring summer" also lacks a trailing space.
Second, the string " " in the println statement is created before any of the code is able to run. This constant is loaded while the class is loaded that contains it. This make me believe that the answer is 9 String objects instead of 8. This string must exist prior to any of the example code to execute.
Third, the example states that "summer ", "fall", "spring fall", "spring summer spring", "winter" and eventually "spring" are lost, while "spring", "summer ", "fall", "winter " are still referenced by the constant pool and not lost. To keep constant pool complexity a bit out of the picture, I could understand why this is done, but this gives the problem that say, the string "spring fall" is treated in the same way as "fall". While "spring fall" will be eligible for the GC, "fall" will not be as long as it is referenced by the constant pool.
Joined: Jun 09, 2008
On page 425:
We got a nice new String out of the deal, but the downside is that the old String "abc" has been lost in the String pool, thus wasting memory. If we are using a StringBuffer instead of a String, the code would look like this:
If I get things right, in both cases the String objects with content "abc" and "def" are created. There is no lost String object in the first case wasting memory. The String object "abc" is refered by the string constant pool and x is set to refer to it, there is no additional String object that goes to waste in comparison to the second scenario.
Is this correct?
subject: Doubt in K&B SCJP 5: topic Important Facts About Strings and Memory