10.4 C
Canberra
Friday, September 20, 2024

String comparisons in Java | InfoWorld



The intern() methodology

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() 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 comprises 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™ 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 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:

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

[td_block_social_counter facebook="tagdiv" twitter="tagdivofficial" youtube="tagdiv" style="style8 td-social-boxed td-social-font-icons" tdc_css="eyJhbGwiOnsibWFyZ2luLWJvdHRvbSI6IjM4IiwiZGlzcGxheSI6IiJ9LCJwb3J0cmFpdCI6eyJtYXJnaW4tYm90dG9tIjoiMzAiLCJkaXNwbGF5IjoiIn0sInBvcnRyYWl0X21heF93aWR0aCI6MTAxOCwicG9ydHJhaXRfbWluX3dpZHRoIjo3Njh9" custom_title="Stay Connected" block_template_id="td_block_template_8" f_header_font_family="712" f_header_font_transform="uppercase" f_header_font_weight="500" f_header_font_size="17" border_color="#dd3333"]
- Advertisement -spot_img

Latest Articles