The intern()
method is defined in the java.lang.String
class. intern()
returns a reference to a string object. On invocation of the intern()
method, if the string object with the same value already exists in the String Pool, the reference to the existing string object is returned. Otherwise, if the string is not present in the String Pool, a new string object and its reference points are added.
public String intern()
The method does not take any parameters.
The following is a code example demonstrating the usage of the intern()
method in Java.
// String.intern() method examplepublic class Main {public static void checkEqual(String first, String second) {if (first != second) {System.out.println("references point to differnt objects in memory");} else {System.out.println("references point to the same objects in String Pool");}}public static void main(String[] args){// string literals are crated in String PoolString str1 = "Hello";// object instantiation using new allocates Heap memoryString str2 = new String("Hello");// call to intern method gets the reference from String PoolString str3 = new String("Hello").intern();checkEqual(str1, str2);checkEqual(str1, str3);}}
The diagram below depicts the memory allocation upon execution of the program above.
String str1 = "Hello";
Here, str1
is defined as a string literal.
Internally, the intern()
method is invoked by the Java Virtual Machine, and the object is created in the String Pool.
String str2 = new String("Hello");
As str2
is instantiated using the new
operator, it will get allocated to the heap.
String str3 = new String("Hello").intern();
For str3
, the intern()
method is called on the newly created string, so it will refer to the string from the String Pool.