Possible Duplicate:
Java Strings and StringPool
I created two Strings
String s1="MyString";
String s2=new String("MyString");
System.out.println(s1==s2);
it prints "false" . we know that String pool doesn’t create two Objects for same String literal.
Then what is happening here? It’s creating two different String Objects(literals) in String pool for same String literal “MyString”.
I know equals() method returns true here.
but when we use == it should compare two references and they should refer to the same
String Object in String constant pool.
Why It is not refering to the existing String object in the String pool even if it finds a match ?.
The first one goes to the pool while the second one is stored on the heap.
Use
s2 = s2.intern();to make it returntrue.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.As a reference, here is what the
String.intern()documentation says: