Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Hom many Objects are created ???

 
anil kumar
Ranch Hand
Posts: 447
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 288
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
John Stone
Ranch Hand
Posts: 332
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"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
Posts: 447
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
------------------------------------
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
Posts: 12183
34
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic