The first one goes to the pool while the second one is stored on the heap.
Use s2 = s2.intern();
to make it return true
.
When you do an intern()
on the string, the JVM ensures that the string is present in the pool. If it doesn't yet exist, it is created on the pool. Otherwise, the already existing instance is returned. I think this explains the ==
behaviour.
String s1="MyString";
String s2=new String("MyString");
s2 = s2.intern();
System.out.println(s1==s2);
As a reference, here is what the String.intern()
documentation says:
/**
* Returns a canonical representation for the string object.
* <p>
* A pool of strings, initially empty, is maintained privately by the
* class <code>String</code>.
* <p>
* When the intern method is invoked, if the pool already contains a
* string equal to this <code>String</code> object as determined by
* the {@link #equals(Object)} method, then the string from the pool is
* returned. Otherwise, this <code>String</code> object is added to the
* pool and a reference to this <code>String</code> object is returned.
* <p>
* It follows that for any two strings <code>s</code> and <code>t</code>,
* <code>s.intern() == t.intern()</code> is <code>true</code>
* if and only if <code>s.equals(t)</code> is <code>true</code>.
* <p>
* All literal strings and string-valued constant expressions are
* interned. String literals are defined in section 3.10.5 of the
* <cite>The Java™ Language Specification</cite>.
*
* @return a string that has the same contents as this string, but is
* guaranteed to be from a pool of unique strings.
*/
public native String intern();