intern() String Example

intern() String Example

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.

intern()

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

Leave a Reply

Your email address will not be published. Required fields are marked *