What makes reference comparison (==) work for some strings in Java?

I have following lines of codes to compare String. str1 not equal to str2, which is understandable since it compares object reference. But then why s1 is equal to s2?

String s1 = "abc";
String s2 = "abc";

String str1 = new String("abc");
String str2 = new String("abc");

if (s1==s2)
    System.out.println("s1==s2");           
else
    System.out.println("s1!=s2");

if (str1==str2)
    System.out.println("str1==str2");           
else
    System.out.println("str1!=str2");

if (s1==str1)
    System.out.println("str1==s1");         
else
    System.out.println("str1!=s1");

Output:

  s1==s2
  str1!=str2
  str1!=s1 

Solution 1:

The string constant pool will essentially cache all string literals so they're the same object underneath, which is why you see the output you do for s1==s2. It's essentially an optimisation in the VM to avoid creating a new string object each time a literal is declared, which could get very expensive very quickly! With your str1==str2 example, you're explicitly telling the VM to create new string objects, hence why it's false.

As an aside, calling the intern() method on any string will add it to the constant pool, so long as an equivalent string isn't there already (and return the String that it's added to the pool.) It's not necessarily a good idea to do this however unless you're sure you're dealing with strings that will definitely be used as constants, otherwise you may end up creating hard to track down memory leaks.

Solution 2:

s1 and s2 are String literals. When you create a new String literal the compiler first checks whether any literal representing the same is present in the String pool or not. If there is one present, the compiler returns that literal otherwise the compiler creates a new one.

When you created String s2 the compiler returns the String s1 from the pool as it was already created before. That is the reason why s1 and s2 are same. This behaviour is called interning.