Saturday, 3 March 2018

String interning in Java

We can store only one copy of each distinct string value in pool with string Interning method.
Java String object has public method intern() method to do this.
String internally maintain pool of strings where all strings are interned automatically.

When we call intern() method on String, first it will check whether string pool has this object or not  and it will return reference of string if same string is available in pool otherwise new object will be added to pool and return reference of it.

String Intern() method will help us to compare two string by using == operator by looking into string pool and it is very faster than equals() method for comparison. Generally java will advise to use == operator to compare rather than equals() method why because == operator will compare memory locations where as equals() will compare against content of two strings.

Even though java automatically intern the strings, we can use intern() method to compare two strings and two string are not constants.

Intern() method should be used on string constructed with new String() and compared with == operator.

package com.sample.javase.testing;

public class StringInternTest {

    public static void main(String[] args) {
        String s ="java";
        String s1 = "java";
        String s2 = new String("java");
        String s3 = s2.intern();
        //here : s2 will return existing reference bcoz java is already there in pool
        System.out.println(s1 == s);//true
        System.out.println(s1 == s2);//false
        System.out.println(s2 == s3);//false
        System.out.println(s1 == s3);//true
       
    }
}

No comments:

Post a Comment