user84592 user84592 - 1 month ago 7
Java Question

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

Answer

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 (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.