Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do strings used in a System.out.println also create new immutable objects?

So I'm studying for the SCJP from the Kathy Sierra book. In the chapter for strings, this is a question:

String s1 = "spring ";
String s2 = s1 + "summer ";
s1.concat( "fall ");
s2.concat(s1);
s1 += "winter";
System.out.println(s1+" "+s2);
---------------------------
What's the output, and how many string objects and ref variables are created?

The output is spring winter spring summer and there's two reference variables, that's fine.

Then it says there are eight string objects created (spring, summer, spring summer... etc) INCLUDING the ones that are lost due to nothing referencing them.

However, it does not include anything from the last sysout.

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? Or will it simply be passed to the string buffer for display, and not create new objects?

This is obviously very basic and I looked elsewhere but nothing directly answered this. From my understanding, it should create new objects there too, but I need to be sure for the exam! Thoughts?

Thanks, in advance!

like image 216
Nilay Panchal Avatar asked May 22 '13 11:05

Nilay Panchal


1 Answers

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) and s1 + " " + 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";
like image 183
Jon Skeet Avatar answered Sep 30 '22 03:09

Jon Skeet