String Interning — What, Why, and When?
Learn about string interning, a method of storing only one copy of each distinct string value, which must be immutable.
Join the DZone community and get the full member experience.
Join For FreeWhat is String Interning?
String Interning is a method of storing only one copy of each distinct String Value, which must be immutable.
In Java, String
class has a public
method intern()
that returns a canonical representation for the string object. Java’s String
class privately maintains a pool of strings, where String
literals are automatically interned.
When the
intern()
method is invoked on aString
object it looks the string contained by thisString
object in the pool, if the string is found there then the string from the pool is returned. Otherwise, thisString
object is added to the pool and a reference to thisString
object is returned.
The intern()
method helps in comparing two String
objects with ==
operator by looking into the pre-existing pool of string literals, no doubt it is faster than equals()
method. The pool of strings in Java is maintained for saving space and for faster comparisons.Normally Java programmers are advised to use equals()
, not ==
, to compare two strings. This is because ==
operator compares memory locations, while equals()
method compares the content stored in two objects.
Why and When to Intern ?
Though Java automatically interns all Strings by default, remember that we only need to intern strings when they are not constants, and we want to be able to quickly compare them to other interned strings. The intern()
method should be used on strings constructed with new String()
in order to compare them by ==
operator.
Let’s take a look at the following Java program to understand the intern() behavior.
public class TestString {
public static void main(String[] args) {
String s1 = "Test";
String s2 = "Test";
String s3 = new String("Test");
final String s4 = s3.intern();
System.out.println(s1 == s2);
System.out.println(s2 == s3);
System.out.println(s3 == s4);
System.out.println(s1 == s3);
System.out.println(s1 == s4);
System.out.println(s1.equals(s2));
System.out.println(s2.equals(s3));
System.out.println(s3.equals(s4));
System.out.println(s1.equals(s4));
System.out.println(s1.equals(s3));
}
}
//Output
true
false
false
false
true
true
true
true
true
true
Published at DZone with permission of Saurabh Chhajed, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments