aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes doubt in string question in  Kathy Sierras SCJP book Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "doubt in string question in  Kathy Sierras SCJP book" Watch "doubt in string question in  Kathy Sierras SCJP book" New topic
Author

doubt in string question in Kathy Sierras SCJP book

manas ranjan mandal
Ranch Hand

Joined: Apr 02, 2008
Posts: 97
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

Joined: Jul 08, 2003
Posts: 24166
    
  30

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.


[Jess in Action][AskingGoodQuestions]
Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952


Where is the declaration of x and y here ? How can anybody know number of string objects without declaration of x and y?


SCJP 6
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24166
    
  30

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

Joined: Oct 16, 2008
Posts: 952
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: doubt in string question in Kathy Sierras SCJP book
 
Similar Threads
How many string objects ?
How many String objects ... ?!
String Objects
Creating String Objects
String Object query