String literal pool
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
When we create a String
String s = new String("abc");
two objects are created. One goes to the String literal pool and the other is present in the nonpool and s points to the nonpool object.
When we again say
String s1 = "abc";
will s1 point to the object "abc" already present in the pool ?
Hope I was clear
Thank you
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
String s = new String("xyz"); // creates two String objects - common fallacy suggests otherwise I've noticed, but the spec. is quite clear (as are observations when profiling).
Tony Morris
Java Q&A (FAQ, Trivia)
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
Not always pointing to existing object
Am I getting more confused?
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
The new operator always creates a new object on the heap. Unless you use the String.intern() method, that object will never be in the constant pool. So, "s1==s2" will always be false.
It is true that "String s1 = new String("ABC");" puts the String literal "ABC" in the constant pool, but that literal is only used as the argument to the String() constructor. The value assigned to s1 is a reference to the String object created by "new String("ABC")", not a reference to the String literal "ABC".
What he means is that whenever you use "new String("ABC")", a new object will always be created on the heap. In addition to this, following the rules of the SLP, a literal will be added to it. In effect, whenever you compare two strings, and one of them has been created using new, they will never refer to the same object. So, any comparison between the two String objects, (s1==s2), will always return false, if they have been created in the following way:
String s1 = "ABC";
String s2 = new String("ABC");
Hope this clears the doubt.
Regards,<br />Subhash Bhushan.
-
-
Number of slices to send:Optional 'thank-you' note:
-
-
Originally posted by Steven Bell:
I have not yet seen anything that says when you create a String with new String("string") it creates two objects. As for the pool, I don't think it is a pool of Objects, but rather a pool of references to Objects (Strings).
It does create 2 objects (unless there's already a String "string" in the String literal pool in which case that one gets reused), one in the String literal pool and one on the heap.
42
| I claim this furniture in the name of The Ottoman Empire! You can keep this tiny ad: The new gardening playing cards kickstarter is now live! https://www.kickstarter.com/projects/paulwheaton/garden-cards |










