• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String Objects Confusion

 
thomas jacob
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
13. String x = new String("xyz");
14. y="abc";
15. x=x+y;

Question: How many objects are created

Answer is 4
The K&B says the 13 line creates 2 and the following 14 and 15 line creates one string object each.

Can anybody tell how line 13. creates two string objects.
 
Joe Sondow
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, an object is created for the string literal "xyz", which acts as a reference to the String object. Then that reference "xyz" is passed to the String constructor, which is called with the new operator, thus creating a second object.

Put another way, "xyz" refers to an object, and new String("xyz") refers to another object.
 
thomas jacob
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
fair enough thanks
 
Girish Bal
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
joe, does that mean that will return false?
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic