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!
javap -c
, and check what bytecode it compiles to. Should be an implicitStringBuffer
that ultimately getstoString()
called on it, which should answer the question. – Mandler