aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Hom many Objects are created ??? 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 "Hom many Objects are created ???" Watch "Hom many Objects are created ???" New topic
Author

Hom many Objects are created ???

anil kumar
Ranch Hand

Joined: Feb 23, 2007
Posts: 447
Given the following,
13. String x = new String("xyz");
14. y = "abc";
15. x = x + y;
how many String objects have been created?


My Answer is 3,but the source saying 4.
source---->Knowledge Testing Engine
How come ?
Mark Smyth
Ranch Hand

Joined: Feb 04, 2004
Posts: 288
Originally posted by anil kumar:
Given the following,
13. String x = new String("xyz");
14. y = "abc";
15. x = x + y;
how many String objects have been created?


My Answer is 3,but the source saying 4.
source---->Knowledge Testing Engine
How come ?


4 is the correct answer

String x = new String("xyz"); // String "xyz" placed on literal pool, also String "xyz" created on heap by new operator and assigned to x

14. y = "abc"; String "abc" placed on literal pool and assigned to y
15. x = x + y; String "xyzabc" created on heap and assigned to x


SCJP<br />SCJD
John Stone
Ranch Hand

Joined: May 04, 2007
Posts: 332
"xyz" -> created in string pool
x = new String() -> new string
"abc" -> created in string pool
x = x+y -> new string built with StringBuilder
anil kumar
Ranch Hand

Joined: Feb 23, 2007
Posts: 447
------------------------------------
String x = new String("xyz"); // String "xyz" placed on literal pool, also String "xyz" created on heap by new operator and assigned to x
---------------------------------------

should we consider two objects here.
I think here only one object is created
i know that one is there pool.Should we consider that also

Thanks Anil Kumar
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11311
    
  16

Originally posted by anil kumar:
------------------------------------
String x = new String("xyz");
---------------------------------------
should we consider two objects here.
I think here only one object is created


This line creates two String objects. EVERY unique literal creates an object in the pool. so, the fact that "xyz" is on this line causes one object.

EVERY time you see the word 'new', a new object is created. that is the whole point of that word. So, a SECOND String object does indeed get created on this line.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
 
Don't get me started about those stupid light bulbs.
 
subject: Hom many Objects are created ???