On page 419, the question:
What is the output? For extra credit, how many String objects and how many reference variables were created prior to the println statement?
is given for the code:
String s1 = "spring ";
String s2 = s1 + "summer ";
s1.concat("fall ");
s2.concat(s1);
s1 += "winter ";
System.out.println(s1 + " " + s2);
with the answer:
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.