My question is, in the last line of code, since s1 and s2 are being concat with a space, doesn't this also create new objects?
Yes, it creates a 10th string.
Note that this piece of code in itself only necessarily creates 5 strings - if you run it several times in the same JVM, it will create 5 new strings each time you call it. The string literals won't create a new string each time the code runs. (The same string object is reused for "spring "
each time, for example.)
There are 10 strings in the code you've given:
- 5 literals: "spring ", "summer ", "fall ", "winter " and " "
- 5 concatenation results:
s1 + "summer"
,s1.concat("fall ")
,s1 + winter
(with compound assignment) ands1 + " " + s2
.
As I've just commented, a string literal appearing in code doesn't always involve a separate string. For example, consider:
String x = "Foo" + "Bar";
You might expect that to involve three string objects - one for each of the literals, and one for the concatenation. In fact, it only involves one, because the compiler performs the concatenation at compile-time, so the code is effectively:
String x = "FooBar";