Java String intern() Method Tutorial

In this section, we will learn what the String intern() method is and how to use it in Java.

What is Java String intern() Method?

The object that we create from the String class via the `new` keyword will be stored in the heap area of the memory. If we want to get a copy of this string object and store it in the string pool, we can use the `intern()` method.

Note: you can check the string pool section for more details.

Java intern() Method Syntax:

public String intern()

intern() Method Parameters:

The method does not take an argument.

intern() Method Return Value:

The return value of this method is a reference to the newly created string in the string-pool.

Note: if inside the string pool there’s an object with the same content, only the reference of that object will return and no new object will be created.

intern() Method Exceptions:

This method does not throw an exception.

Example: using String intern() method

public class Simple {

    public static void main(String[] args)  {
       String s1 = new String ("Hi");
       String s2 = s1.intern();
        System.out.println(s1 == s2);
    }
}

Output: false

Note: please check the string pool section if you’re not familiar with the concept and also wondering why the result of the `s1==s2` comparison is false?!

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies