When can we use intern() method of String class in Java?


The intern() method of String class can be used to deal with the string duplication problems in Java. Using intern() we can save a lot of memory consumed by duplicate string instances. A string is duplicate if it contains the same content as another string but it can be occupied different memory locations.

We know that JVM maintains a separate heap memory for string literals for the performance. Once we declare a string literal it will go to this pool and if another variable is assigned with the same literal value, it will be picked from the pool instead of creating a new object and storing it in heap. But if the string is declared using a new constructor, a new object will be made even if literal exists in the pool. To avoid this and to force JVM to pick the literal from the pool we use intern() method.

Java automatically interns all the strings by default. The intern() method can be used in strings with new String() in order to compare them by the == operator.

Example

Live Demo

public class StringInternClassTest {
   public static void main(String[] args) {
      String s1 = "Tutorix";
      String s2 = "Tutorix";
      String s3 = new String("Tutorix");
      final String s4 = s3.intern();
      String s5 = "?Tutorix".substring(1);
      String s6 = s5.intern();
      System.out.println(s1 == s2);
      System.out.println(s2 == s3);
      System.out.println(s3 == s4);
      System.out.println(s1 == s3);
      System.out.println(s1 == s4);
      System.out.println(s1 == s5);
      System.out.println(s1 == s6);
      System.out.println(s1.equals(s2));
      System.out.println(s2.equals(s3));
      System.out.println(s3.equals(s4));
      System.out.println(s1.equals(s4));
      System.out.println(s1.equals(s3));
   }
}

Output

true
false
false
false
true
false
true
true
true
true
true
true

Updated on: 07-Feb-2020

310 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements