Home Update String comparisons in Java

String comparisons in Java

28
equal, equals, two hands holding the bars of an 'equals' sign

The intern() technique

To retailer a String in a String pool, we use a method known as String interning. Here’s what Javadoc tells us in regards to 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 accommodates a
     * string equal to this {@code String} object as decided by
     * the {@hyperlink #equals(Object)} technique, 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 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 after we use the new key phrase to drive the creation of two Strings:



Source hyperlink

LEAVE A REPLY

Please enter your comment!
Please enter your name here