A thread in the java forum on Facebook posed the following question:
What is an intern() method in the String class how does it work..?
There are many explanations,but following is the best which I found/know.
String s1 = new String(“Hello”);
String s2 = new String(“Hello”);
System.out.println(s1.equals(s2)); // true (Since both objects contain the same data.)
System.out.println(s1==s2); // false SINCE s1 & s2 are two different instances.
System.out.println(s1.intern()==s2.intern()); // TRUE…EXPLANATION BELOW.
the equals() method can be fairly slow, as it involves a character-by-character comparison of the strings.Since the == method compares identity, all it has to do is compare two pointers to see if they are the same, and obviously it will be much faster than equals().
So if we are going to be comparing the same strings “REPEATEDLY”, we can get a significant performance advantage by reducing it to an identity comparison rather than an equality comparison.
The basic algorithm is:
1) Create a hash set of Strings
2) Check to see if the String we’re dealing with is already in the set
3) If so, return the one from the set
4) Otherwise, add this string to the set and return it
After following this algorithm, we are guaranteed that if two strings contain the same characters, they are also the same instance.
This means that we can safely compare strings using == rather than equals(),gaining a significant performance advantage with “REPEATED” comparisons.
Java already includes an implementation of the algorithm above. It’s the intern() method.
All constant strings that appear in a class are automatically interned.
protected final static String fVersionSymbol = “version”.intern();