Java SE 7 Docs: When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
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 tried a sample java program and realized that on invoking intern over a String object (created via new operator), a new String object is created in String Literal Pool and its reference is returned.
It seems like a new object is created on calling intern() over s1, having its reference returned to variable on stack s4 and added to String Literal Pool table as well.
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
As Joe mentioned, the contract of intern method doesn't mention that the String object on which you call the method itself is added to the pool. You get this guarantee
Java Docs wrote:It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.
So you don't get this guarantee:
s.intern() == s
Prior to JDK 7, String constant pool used to reside in PermGen memory, so this code will create 2 String objects, 1 in Heap and 1 in PermGen
String s = new String("pqr");
This is why s.intern() == s cannot be true as s resides in the heap and s.intern() in the PermGen. After JDK 7 this was changed and String constant pool now resides in the heap. But maybe that's a reserved part of the heap for constant pool and that's why the same String is not added to the pool, instead a new String with same content is added to the pool...