String intern() function and String Pool

Let’s start with the  JVM spec..

The Java programming language requires that identical string literals (that is, literals that contain the same sequence of code points) must refer to the same instance of class String. In addition, if the method String.intern is called on any string, the result is a reference to the same class instance that would be returned if that string appeared as a literal.

Elucidating, if there are more than one string literal with the same value, they share the memory.

Consider the example. An application X processes the results from a questionnaire which expects an YES/NO response. Adding on, there are more than a billion replies. If you store  all those ‘YES’ and ‘NO’ values separately, you’ll end up clogging up your precious memory. So, why don’t we have a single string for ‘YES’ and let the trizillion literals point to it. This is exactly what JAVA does and the table where they store all such string literals is called the String Pool

String sampleOne = "Dylan";
String sampleTwo = "Dylan";
String sampleThree = new String("Dylan");

if(sampleOne == sampleTwo){
System.out.println("One and Two are same");
}

if(sampleOne == sampleThree){
System.out.println("One and Threeo are same");
}

In line 1, we create a String with value “Dylan”. In this process, Java automatically adds a reference of the String “Dylan” to the String Pool. In line 2, when we try to create another string, Java sees if this is already available in the String Pool and just points the literal to the value. But in line 3, we use the new operator to create a string. This is a bit off the mark, the new operator forces Java to ignore the String Pool and create a new instance. This’s the reason why line 6 is printed and line 10 is not… This very well explains why it’s not advisable to use a new operator while creating a String.

intern() method

The docs tells us that the intern() method returns a canonical representation of the string. In other words, using the intern() method, we are forcing Java to check the String pool and return the value of the String. Let me modify the above example

String sampleOne = "Dylan";
String sampleTwo = "Dylan";
String sampleThree = new String("Dylan").intern();
if(sampleOne == sampleTwo){
System.out.println("One and Two are same");
}
if(sampleOne == sampleThree){
System.out.println("One and Threeo are same");
}

Here, both line 6 and line 10 is printed.
Instead of creating a new instance in line 3, the intern() forces Java to return the String from String Pool.
Enough Said