The way K&B count objects for this kind of question, the first line creates two -- the quoted String literal, and the "new String()". Line two creates one. Line three creates two, one StringBuilder and one String because it actually compiles into something like
But note that each String contains a char member, and so does the StringBuilder, and so the "real" number might actually be as high as ten; or if you don't count the String literals (which actually get created when the class is loaded,) six.
I'm going to move this to SCJP, because this kind of question is really only relevant there. The SCJP answer is 5.
The question is how many are created in these lines of code; the previous values of x and y are irrelevant.
Joined: Oct 16, 2008
ine 1. String x=new String("xyz");
here one at the time of class loading "xyz" will be created in the heap and its reference will be stored in the constant pool.
second at runtime "xyz" will again created on the heap as new is used and its reference will be stored in the x;
line 2. y="abc";
at compile time "abc" created and its reference will be stored in constant pool as well as in y.
line 3. x=x+y;
at runtime "xyzabc" will be created and its reference will be stored in constant pool as well as in x.
so total 4 objects created.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
subject: doubt in string question in Kathy Sierras SCJP book