I think I understood this from the book. Java has a constant String pool where all strings are added, when the compiler encounters a string it checks to see if it already exists in the pool, and if it does instead of creating it it points the reference to the one in the pool. But if we create the String with keyword new the pool is not checked.
So, if I have string abc in the pool but then do String s = new String("abc"); do I now have 2 abc in the pool, just one but the abc is created as a new object?
Originally posted by shandilya popuru: creating a string with new actually creates 2 objects one on the heap and the other in the pool(if one does not exist prevoiusly) and the reference variable points to the object on the heap
I don't think creating a String with new actually creates two Strings. I don't think one get's created in the pool with new. Even if it was put in the pool that would be a reference and not the object so why create an extra String just to put an unreachable reference in the pool?
The result prints the following on the screen: The result of the comparison s1 == s2 is true The result of the comparison s2 == s3 is false The result of the comparison s1.equals(s3) is true
Note: 1. The == operator checks the references stored in each variable. In this case, s1 and s2 variables contain the same reference to a String literal created in a String pool.
2. Similar to (1.) above, s1 and s3 does not contain the same reference, since the new operator creates a String object containing the literal "abc", whether the literal exists in the String pool or not.
3. The equals() method compares the actual String literals (enclosed within the memory area whose references are stored in variables s1 and s3)not the value of the variables' (s1 and s3) references.
I hope this will give some insight.
Udegbunam Ikechukwu Morah<br />B.Sc.,SCJP, MCP, OCP, PMP<br />Manager, Business COnsulting Group<br />Deep Business Solutions Limited