I would guess there are 11 String objects created:
Compile time
�spring � // line 1
�summer � // line 2
�fall � // line 3
�winter � // line 5
� � // line 6
Runtime
�spring summer� // line 2
�spring fall � // line 3
�spring summer spring � // line 4
�spring winter � // line 5
�spring winter � // line 6
�spring winter spring summer� // line 6
From those 11 objects, only 3 are ever referenced by variables (�spring �, �spring summer� and �spring winter �). And when this code finishes, only 2 are still referenced by variables (�spring summer� and �spring winter �).
Say the compiler optimizes the String concatenations. �To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.�
This might result in something like this:
Then the following String objects would be created:
Compile time
�spring � // line 1
�summer � // line 2
�fall � // line 3
�winter � // line 5
� � // line 6
Runtime
�spring summer� // line 2
�spring fall � // line 3
�spring summer spring � // line 4
�spring winter � // line 5
�spring winter spring summer� // line 6
This still results in 10 String objects. It doesn�t matter if they are discarded right away since the question was how many String objects are created.
Now, concerning the K&B book, the question was: how many String objects and how many reference variables are created prior to the println statement. This is then: 2 reference variables (s1 & s2) and 8 objects (�spring �,�summer �,�fall �,�winter �,�spring summer�, �spring fall �,�spring summer spring � and �spring winter �).