Warning: Undefined array key "amp-addthis" in /home/tgagmvup/onlinestudy.guru/wp-content/plugins/addthis/backend/AddThisSharingButtonsFeature.php on line 101
lang="en-US"> What is intern() - onlinestudy.guru
Site icon onlinestudy.guru

What is intern()

n Java, the intern() method is used to place a String object into the internal pool of strings, also known as the string pool. This string pool is a special area in the Java heap memory where literal strings are stored. When you create a string literal (e.g., "hello"), Java automatically stores it in the string pool. However, strings created using the new keyword (e.g., new String("hello")) are not automatically interned unless you explicitly call intern() on them.

package strings;

public class InternMethodDemo {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = new String("hello");

        System.out.println(s1 == s2);          // false - s1 and s2 point to different objects
        System.out.println(s1.equals(s2));     // true - s1 and s2 have the same content

        String s3 = s2.intern();

        System.out.println(s1 == s3);          // true - s1 and s3 point to the same interned string object

    }
}

When to Use intern():

By understanding how intern() works, you can leverage it effectively to optimize memory usage and ensure predictable string comparison behavior in your Java applications.

Exit mobile version