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

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.

Leave a Comment