Reputation: 2679
Im studying and getting ready for a Java SE 6 certification. Im using Kathy Sierra and Bert Bates book "Sun Certified Programmer for Java 6 Study Guide". Im actually at Strings, I/O and Parsing.
They present an example of the kind of devilish String question i might expect to see on the exam:
String s1 = "spring ";
String s2 = s1 + "summer ";
s1.concat("fall ");
s2.concat(s1);
s1 += "winter ";
System.out.println(s1 + " " + s2);
What is the output? For extra credit, how many String objects and how many reference variables were created prior to the println statement?
Answer: The result of this code fragment is spring winter spring summer. There are two reference variables, s1 and s2. There were 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 winter" (at this point "spring" is lost). Only two of the eight String objects are not lost in this process.
My question in the title is very specific. As you can see, they say there were a total of 8 String
objects, but, what happens at the println method call ? It is passing a String object reference as argument, so, the value of s1 plus s2 should create other String object, since its immutable, increasing the count to 9.
But (possibly even more) shouldn't the empty String (" ") between the value of s1 and s2 create other object, increasing the count to 10 ?
It counted when they did this:
s1.concat("fall ");
So, why not this:
s1.concat(s1 + " " + s2);
or the real one, this:
System.out.println(s1 + " " + s2);
Upvotes: 3
Views: 1913
Reputation: 8246
Because of the statement with the operative word prior: '
prior to the println statement
8 String
objects were created before (prior to) the println
as you described. Another 2 were created on the println
, " "
and spring winter spring summer
String s1 = "spring "; // "spring" created, reference s1 changed
String s2 = s1 + "summer "; // "summer", "spring summer" created, "summer" not saved, reference s2 changed
s1.concat("fall "); // "fall", "spring fall" created but not saved
s2.concat(s1); // "spring summer spring" created but not saved
s1 += "winter "; // "winter", "spring winter" created, reference s1 changed
System.out.println(s1 + " " + s2); //" ", "spring winter spring summer" created, " " not saved
NOTE: "created" doesn't mean created at this point in the code, just that this piece of code will ask that it be created.
Upvotes: 4