Almost every java developer finds one fine morning that he cannot compare String with "==" as he has been doing with int or char. Then either he finds out or someone kindly tells him that objects cannot be compared with "==". He has to use equals(Object) method. However rarely, if ever, he realizes that it is possible to use == to compare two String for equality. There are two greatThe benefits of being able to use == for String comparison - improved performance and memory usage reduction.

To achieve this you need to call the magic method - intern() on a String.

String class internally maintains a private pool of strings which are initially empty.

When the intern() method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

All literal strings and string-valued constant expressions are interned.

So if you compare an interned String with another interned String or String constant then you can safely use == instead of (or in addition to) equals(Object) method.

This is widely used while processing large XML documents where the tags are interned for faster comparison and lower memory consumption.

Update: Based two comments below by Christian and Markus, I re-evaluated the validity of touted performance benefit. With JDK 1.5 (I tested with) there isn't any performance difference between equals(Object) and == for String. It is most likely because of equals implementation which first does a == comparison anyway as pointed out by Markus Kohler. Thanks for correcting me guys.

PS. It is amazing how Java is improving over the versions. Several previous assumptions of performance are not valid anymore. There goes another. I wonder when String concatenation with + operator will follow suit.