When and why should we use intern method of string class

String.intern() method can be used to to deal with String duplication problem in Java. By carefully using the intern() method you can save a lot of memories consumed by duplicate String instances. A string is duplicate if it contains the same content as another string but occupied different memory location e.g. str1 != str2 but str1.equals(str2) is true.

As we know JVM maintains a separate heap memory for string literals for performance boost. So a string literal once declared will go to this pool and if another variable is assigned same literal value, it will be picked from the pool instead of creating a new object and storing it in heap. But if string is declared using new constructor a new object will be made even if literal exists in the pool. To avoid this and to force JVM to pick the literal from the pool we use intern() method.

Though Java automatically interns all Strings by default, remember that we only need to intern strings when they are not constants, and we want to be able to quickly compare them to other interned strings. The intern() method should be used on strings constructed with new String() in order to compare them by == operator.

public static void main(String[] args) {
        String s1 = "Test";
        String s2 = "Test";
        String s3 = new String("Test");
        final String s4 = s3.intern();
        String s5 = "?Test".substring(1);
        String s6 = s5.intern();
        System.out.println(s1 == s2);
        System.out.println(s2 == s3);
        System.out.println(s3 == s4);
        System.out.println(s1 == s3);
        System.out.println(s1 == s4);
        System.out.println(s1 == s5);
        System.out.println(s1 == s6);

Output would be :


Prior to Java 6, uncontrolled usage of String.intern() method can cause java.lang.OutOfMemory: PermGen space because String pool was physically located on PermGen area of Java heap, which is quite small in many JVM (32M to 96M) and fixed. From Java 7 onward, the intern() method has become even more useful because String pool is relocated to main heap space of JVM. This will help to further reduce String duplication by using String.intern() method.

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

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