The intern() methodology
To retailer a String
in a String
pool, we use a way known as String interning. Right here’s what Javadoc tells us concerning the intern()
methodology:
/**
* Returns a canonical illustration for the string object.
*
* A pool of strings, initially empty, is maintained privately by the
* class {@code String}.
*
* When the intern methodology is invoked, if the pool already accommodates a
* string equal to this {@code String} object as decided by
* the {@hyperlink #equals(Object)} methodology, then the string from the pool is
* returned. In any other case, 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 provided that {@code s.equals(t)} is {@code true}.
*
* All literal strings and string-valued fixed expressions are
* interned. String literals are outlined in part 3.10.5 of the
* The Java&commerce; Language Specification.
*
* @returns a string that has the identical contents as this string, however is
* assured to be from a pool of distinctive strings.
* @jls 3.10.5 String Literals
*/ public native String intern();
The intern()
methodology is used to retailer String
s in a String
pool. First, it verifies if the String
you’ve created already exists within the pool. If not, it creates a brand new String
within the pool. Behind the scenes, the logic of String
pooling is predicated on the Flyweight sample.
Now, discover what occurs after we use the new
key phrase to pressure the creation of two String
s: