What is the role of the String intern() method in java?


A String is a class in Java which stores a sequence of characters, it belongs to the java.lang package. Once you create a String object you cannot modify them (immutable).

Storage

All String objects are stored in a separate memory location in the heap area known as, String Constant pool.

Whenever you define a String value JVM creates a String object with the given value in the String constant pool. Therefore, if you run the above program two String values are created in the String constant pool.

The intern() method

This method returns value of the current String from the pool of unique String values. Whenever you invoke this method on a particular String, if the String constant pool already contains a String equal to it (as per the equals method of the Object class), it will be returned. If not, the current String is added to the String constant pool returning a reference to it.

i.e. if you invoke this method on two Strings with same contents it is guaranteed that they share the same memory.

This method comes handy to reduce the memory occupied in case of several duplicate values.

Example

In the following we are creating two Strings (using new keyword) with same content and comparing them with using the “==” operator. Though both objects have same value, since they don’t refer to same object (memory) the result will be false.

public class InternExample {
   public static void main(String args[]) {
      String str1 = new String("Hello");
      str1 = str1.intern();
      String str2 = "Hello";
      str2 = str2.intern();
      System.out.println(str1.equals(str2));
   }
}

Output

false

But, if you invoke intern method on the both objects before comparing them, since it makes sure that both objects share same memory if they have same content the result will be true.

public class InternExample {
   public static void main(String args[]) {
      String str1 = new String("Hello");
      str1 = str1.intern();
      String str2 = new String("Hello");
      str2 = str2.intern();
      System.out.println(str1==str2);
   }
}

Output

true

Updated on: 10-Oct-2019

77 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements