String in Java V: The intern Method

In this lesson we will look at the job hunters’ favorite intern() method. We have already seen a few important methods in the previous lesson.

The intern() Method

intern() is a method frequently discussed in job interviews. Therefore, we will study the method is some what greater detail than other methods. Conversely, if you are interviewing candidates watch out for candidates who say “intern() returns canonical representation of string” but can’t elaborate on that.

What does Java String’s intern() method do?

In our first lesson on Java Strings, we saw that Java strings can be created either by using literals or using new . The strings created by using literals or string expressions are stored in string (constant) pool. Every time the string is required,  a reference to the existing is returned. Strings created using the new operator on the other hand are not pooled. Every time new is invoked a new String object is instantiated.

String pool in the earlier JDK releases was a part of PermGen space. (Reference: our first lesson on Strings) Therefore, it was a prized real estate. Although string pool is garbage collected, you want to ensure that only frequently used strings are pooled. After all, there is no point in pooling and caching something that will never be required again.

Therefore, in earlier JDKs you did not put your string in the pool unless you were very sure it is frequently used. But this posed a problem. Whether a string is pooled or not depends on how it is created. So, by the time you discover that you should be pooling a particular string, it might already be too late.

Java came up with a facility of pooling strings that are created using new operator. This is achieved using the intern() method.

The intern() method puts a string in the string pool and returns a reference to the pooled string.

Therefore, the usage pattern now is to create strings using the new operator, and if the string is used frequently to pool it using the intern() method.

Example of intern() Method

Here is an example of usage of the method.

The output of the above code is

The code above demonstrates how to intern-ize a string that becomes frequently used.

As soon as “CodingRaptor.com” became theProgrammingWebsite, theJavaWebsite and theHadoopWebsite, we decided to intern-ize “CodingRaptor.com” and use the same String object all across.

Leave a comment

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