Tuesday, January 19, 2016

How The Strings Are Stored In The Memory?


We all know that JVM divides the allocated memory to a Java program into two parts. one is Stack and another one is heap. Stack is used for execution purpose and heap is used for storage purpose. In that heap memory, JVM allocates some memory specially meant for string literals. This part of the heap memory is called String Constant Pool.


Whenever you create a string object using string literal, that object is stored in the string constant pool and whenever you create a string object using new keyword, such object is stored in the heap memory.
When you create string objects like below, they will be stored in the String Constant Pool.

String s1 = "abc";
String s2 = "xyz";
String s3 = "123";
String s4 = "A";

And when you create string objects using new keyword like below, they will be stored in the heap memory.


String s5 = new String("abc");
char[] c = {'J', 'A', 'V', 'A'};
String s6 = new String(c);
String s7 = new String(new StringBuffer());

This is how String Constant Pool looks like in the memory.

Intern() in String

/*s1 and s2 being called without new operator , thus resides in String constant pool
and since both've same value, both refer to same object*/

/* s3 is different object with its own value, but when called with intern() , it firstly checks
if there is any object with same value in string pool. In case if its present, it refer to the same String*/

public class Test {
            public static void main(String[] args) {
                        String s1 = "java";
                        String s2 = "java";
                        String s3 = new String("java").intern();
                        System.out.println("s1 == s2" + (s1 == s2)); // returns true
                        System.out.println("s1 == s3" + (s1 == s3)); // returns true
            }
}

Output :
s1 == s2true
s1 == s3true

No comments:

Post a Comment