Intern String

Posted by

What is Intern String.?When to use Intern Strings ?
Only one String object is shared by all string valued constant expressions with the same character sequence. Such strings are called Intern String, meaning that they share a unique String object if they have the same content.

String can be created by using two ways:
1. Using String literals ex.  String str1=”java2career”;
2. String Constructors- String class have numerous constructor to create and initialize String object.  ex. String str1=new String(“java2career”);

A string literal is a reference to a String object.It can be manipulated any other String Object.Two String literals having same character sequence share a same String object.Such Strings are said to be interned, but if you create String of same character sequence using String constructor, It does not share same String object. It does not mean String constructed with String Constructor can not be Interened, it can be interned by using intern() method.
Java has a special storage area in Java heap for Sring variable.This area is called String pool. When Java program creates a new String using String literal, JVM checks for that String in pool and if String literal is already present in pool than same object is returned instead of creating a new object.If String literal is not present new String object is created and put into the String pool.If String created using new String() constructor, JVM always creates a new String object even if String with same content is available in pool and JVM never put it to the String pool except intern method is called on that String.
Lets see by example.


class internString
    public static void main(String test[]){
        String str1=”java2career”;
        String str2=”java2career”;
        String str3=new String(“java2career”);
        String str4=new String(“java2career”).intern();
        String car=”career”;
        String str5=”java2″+car;//not a compile time constant expression
            System.out.println(“Interned String 1”);
            System.out.println(“Not Interned String3”);
            System.out.println(“Interned String 2”);
            System.out.println(“Not Interned String2”);
            System.out.println(“Interned String 3”);
            System.out.println(“Not Interned String3”);
            System.out.println(“Interned String 5”);
            System.out.println(“Not Interned String5”);


Interned String 1
Not Interned String2
Interned String 3
Not Interned String5
In the last case str5 does not share same object because its not a compile time constant expression.
The advantage of using intern string is memory advantage because in case of these strings you have to keep only one copy of the String’s character in memory, no matter how many times you refer to it.

Leave a Reply