Java provides two basic mechanisms for equality testing. The “==” operator can be used to test primitive values for equality, and can also be used to determine if two object references point to the same underlying object. The equals(Object) method will return true if the argument is equal to the bject on which the method is invoked, where equality is defined by the object’s class semantics.
So in case of strings the operator will only be true if two String references point to the same underlying String object.
The process of converting duplicated strings to shared ones is called interning and is done automatically by Java. This is faster and saves memory.
When the intern() method is invoked on a String, a lookup is performed on a table of interned Strings. If a String object with the same content is already in the table, a reference to the String in the table is returned. Otherwise, the String is added to the table and a reference to it is returned. The result is that after interning, all Strings with the same content will point to the same object. This saves space, and also allows the Strings to be compared using the == operator, which is much faster than comparison with the equals(Object) method, although might be confusing sometimes.
Look at this:
String s = "Reza";
String t = new String("Reza");//forces creating a new object rather than using an intern
System.out.println(s == t);
The output is false although we expected true with interning!
It follows that for any two strings s and t, s.intern() t.intern() is true if and only if s.equals(t) is true.
When the intern() method is invoked on a String, a lookup is performed on a table of interned Strings. If a String object with the same content is already in the table, a reference to the String in the table is returned. Otherwise, the String is added to the table and a reference to it is returned. The result is that after interning, all Strings with the same content will point to the same object. This saves space, and also allows the Strings to be compared using the == operator, which is much faster than comparison with the equals(Object) method, although might be confusing sometimes.
Look at this:
String s = "Reza";
String t = new String("Reza");//forces creating a new object rather than using an intern
System.out.println(s == t);
The output is false although we expected true with interning!
It follows that for any two strings s and t, s.intern() t.intern() is true if and only if s.equals(t) is true.