wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String Objects Confusion 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 "String Objects Confusion" Watch "String Objects Confusion" New topic
Author

String Objects Confusion

thomas jacob
Ranch Hand

Joined: May 19, 2005
Posts: 91
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

Joined: Apr 10, 2005
Posts: 195
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.


SCJA 1.0 (98%), SCJP 1.4 (98%)
thomas jacob
Ranch Hand

Joined: May 19, 2005
Posts: 91
fair enough thanks
Girish Bal
Ranch Hand

Joined: Jun 23, 2005
Posts: 52
joe, does that mean that will return false?


Girish B
SCJA 1.0 (86%)
SCJP 1.4 (91%)
OCPJWCD (86%)
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608


Tony Morris
Java Q&A (FAQ, Trivia)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String Objects Confusion