Saturday, 3 March 2018

What is Java String Pool


 String is very special object in java and it is used pool mechanism to store the string literals.
String pooling mechanism is possible only because of String is immutable, and it is implementation of String intern concept.

We can create the String object by using new keyword or assigning text in double Quotes.
When we try to create the string using double quotes, first it will check whether string with same name is already available in pool or not and return reference of it if available or create new string if it is not available in pool.

If we use new keyword to create string, we are forcing to create new object in heap space.
Here we can use Intern method of String or we can refer to other existing string having the same to move this new string to pool.

package com.sample.javase.testing;

public class StringPoolTest {

    public static void main(String[] args) {
       String s ="java";
        String s1 = "java";
        String s2 = new String("java");
        //below : s3 is equal to s and s1 but not s2 becoz it won't create new string in pool as java is //already there in string pool
        String s3 = s2.intern();
        System.out.println(s1 == s);//true
        System.out.println(s1 == s2);//false
        System.out.println(s2 == s3);//false
        System.out.println(s1 == s3);//true
      
      
        String s22 = new String("j2ee");//create new string j2ee in heap and j2ee in pool
        //move j2ee to string pool if j2ee is not availale in pool otherwise return reference of j2ee is //already there in pool
        String s33 = s22.intern();
        //below line won't create new string in pool becasue above line created j2ee in pool. 
//Hence return existing object ref
        String s11 = "j2ee";
        System.out.println(s33 == s11);//true
       
    }

}


String pool is pool of string stored in Heap Memory as shown below

Here String s2 = new String("java"); line will create either two objects or one object.

If the literal "java" is already available in the pool, then it will create one object in heap memory and return it.
If literal "java" is not there in pool, then first it will create java in pool and object in hep memory. total 2 objects will be created and return it

No comments:

Post a Comment