String class is designed with the Flyweight design pattern in mind. Flyweight is all about re-usability without having to create too many objects in memory. A pool of Strings is maintained by the String class. When the intern( ) method is invoked, equals(..) method is invoked to determine if the String already exist in the pool. If it does then the String from the pool is returned instead of creating a new object. If not already in the string pool, a new String object is added to the pool and a reference to this object is returned. For any two given strings s1 & s2, s1.intern( ) == s2.intern( ) only if s1.equals(s2) is true.
Two String objects are created by the code shown below. Hence s1 == s2 returns false.
//Two new objects are created. Not interned and not recommended.
String s1 = new String("A");
String s2 = new String("A");
s1.intern() == s2.intern() returns true, but you have to remember to make sure that you actually do intern() all of the strings that you’re going to compare. It’s easy to forget to intern() all strings and then you can get confusingly incorrect results. Also, why unnecessarily create more objects?
String s1 = "A";
String s2 = "A";
s1 and s2 point to the same String object in the pool. Hence s1 == s2 returns true.
Since interning is automatic for String literals String s1 = “A”, the intern( ) method is to be used on Strings constructed with new String(“A”).