swaraj gupta wrote:My query is regarding the statement in bold: Otherwise, this String object is added to the pool and a reference to this String object is returned..
I agree. The statement is not very clear i.e. it doesn’t go into great detail about what happens when the
intern() method is invoked. To make things worse, the
intern() method is native and so curious people like you and I cannot peruse its Java source code to get more details about its inner workings. However, the great thing about an API documentation is that it saves us from caring about the inner workings of an API.
The most important part of the
String.intern() API documentation is this statement:
Returns:
a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.
This implies that in this code,
s1.intern(), the API documentation makes the following guarantees:
1) the object which
intern() returns is guaranteed to have the same contents as the object referenced by
s1
2) the object which
intern() returns is guaranteed to be from a pool of unique strings
You cannot make any other assumptions.