posted May 23, 2004 02:04 PM
--------------------------------------------------------------------------------
The line below appears in a question in the Study Guide asking how many objects are created in the code example.
13. String x = new String ("xyz")
The answer to the question gives this explanation:
... Line 13 creates two String objects, one referenced by x and the lost string "xyz"
My initial thought was that the object referenced by x *is* "xyz", ie. that there is only one object created.
I understand that, because of the immutability of Strings, concatenation etc. creates new objects. But in this example, it appears that a single String object is being created and assigned to the reference variable x. why does the answer say that "xyz" is lost? And if "xyz" is lost, what is the "one referenced by x" that the answer talks about; what does x refer to?
Thanks,
Keith
Hi Kieth,
I came across this issue in the Kathy Sierra and Bert Bates Book ,
Java 2 Sun Certified Programmer Exam, during my preparation for it:
If you say String s ="abc", This means one string will be created in the string buffer pool.
In your case when you write String p = new("bdf"), "bdf" will be placed in
the normal (non string pool memory) and also in the string pool memory. So
we have two strings. The p reference will refer to the "bdf" in the
non string pool memory. Two strings are created because of the new().
I hope this helps. This is on page 360 of the book mentioned above.