The intern() method
To store a String
in a String
pool, we use a technique called String interning. Here’s what Javadoc tells us about the intern()
method:
/**
* Returns a canonical representation for the string object.
*
* A pool of strings, initially empty, is maintained privately by the
* class {@code String}.
*
* When the intern method is invoked, if the pool already contains a
* string equal to this {@code String} object as determined by
* the {@link #equals(Object)} method, then the string from the pool is
* returned. Otherwise, this {@code String} object is added to the
* pool and a reference to this {@code String} object is returned.
*
* It follows that for any two strings {@code s} and {@code t},
* {@code s.intern() == t.intern()} is {@code true}
* if and only if {@code s.equals(t)} is {@code true}.
*
* All literal strings and string-valued constant expressions are
* interned. String literals are defined in section 3.10.5 of the
* The Java™ Language Specification.
*
* @returns a string that has the same contents as this string, but is
* guaranteed to be from a pool of unique strings.
* @jls 3.10.5 String Literals
*/ public native String intern();
The intern()
method is used to store String
s in a String
pool. First, it verifies if the String
you’ve created already exists in the pool. If not, it creates a new String
in the pool. Behind the scenes, the logic of String
pooling is based on the Flyweight pattern.
Now, notice what happens when we use the new
keyword to force the creation of two String
s: