What does intern() method in java?

Java 8Object Oriented ProgrammingProgramming

The intern() method of the String method returns a canonical representation for the string object. A pool of strings, initially empty, is maintained privately by the class String.

For any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

All literal strings and string-valued constant expressions are interned.


 Live Demo

import java.lang.*;
public class StringDemo {
   public static void main(String[] args) {
      String str1 = "This is TutorialsPoint";
      // returns canonical representation for the string object
      String str2 = str1.intern();
      // prints the string str2
      // check if str1 and str2 are equal or not
      System.out.println("Is str1 equal to str2 ? = " + (str1 == str2));


This is TutorialsPoint
Is str1 equal to str2 ? = true
Published on 12-Feb-2018 08:21:17