String comparisons in Java | InfoWorld

[ad_1]

The intern() technique

To retailer a String in a String pool, we use a way referred to as String interning. Right here’s what Javadoc tells us concerning the intern() technique:


    /**
     * 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 technique is invoked, if the pool already comprises a
     * string equal to this {@code String} object as decided by
     * the {@hyperlink #equals(Object)} technique, 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() technique is used to retailer Strings 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 once we use the new key phrase to power the creation of two Strings:

[ad_2]

Leave a Reply

Your email address will not be published. Required fields are marked *