intern() String Example

November 24, 2014 | class String
How to use intern() is given with Example and Screenshot.

We know the String class maintains a pool of strings. When a new string object is created, its value is placed in the pool. When intern() is called on the existing string object, another new string object is created with the same value reference available in the pool. That is, new string and old existing string refer the same value in the pool. In this case, the equals() method returns true.

java.lang.String class comes with intern() method to save memory for different string objects having the same value.

The signature of intern() method is given as defined in String class.

  • public String intern(): Returns a string reference to this string, or to say, returns a canonical representation for the string object.

In the following example, intern() is used to get a new string str2 from the existing str1.

public class StringMethodDemo
{
 public static void main(String args[])
 {
  String str1 = "ABCDEFGHI";    		

  String str2 = str1.intern();           // see using intern()

  System.out.println("Existing String: " + str1);
  System.out.println("New String: " + str2);
  System.out.println("Comparing with equals(): " + str1.equals(str2));
 }
}

intern()

str1 and str2 refer the same value "ABCDEFGHI" available in the string pool (implicitly managed by JVM).