• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt in string question in Kathy Sierras SCJP book

 
manas ranjan mandal
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
question is as follows
its asking about how many object is created

line 1. String s=new String("xyz");
line 2. y="abc";
line 3. x=x+y;
i think the answer is 3 but the correct answer is 4.how is it possible?

Sorry there should be x in place of s
ine 1. String x=new String("xyz");
line 2. y="abc";
line 3. x=x+y;
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

x = new StringBuilder(x).append(y).toString();

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.
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Where is the declaration of x and y here ? How can anybody know number of string objects without declaration of x and y?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The question is how many are created in these lines of code; the previous values of x and y are irrelevant.
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
4 objects.

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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic