Storage of String in Java
Prerequisite: Strings in Java
As we know both Stack and Heap space are part of Java Virtual Machine (JVM). But these memory spaces are used for different purposes. Stack space contains specific values that are short-lived whereas Heap space used by Java Runtime to allocate memory to objects and JRE classes. In Java, strings are stored in the heap area.
Why Java strings stored in Heap, not in Stack?
Well, String is a class and strings in java treated as an object, hence the object of String class will be stored in Heap, not in the stack area. Let’s go deep into the topic. As we all know we can create string object in two ways i.e
1) By string literal
2) By using ‘new’ keyword
String Literal is created by using a double quote. For Example:
Here the JVM checks the String Constant Pool. If the string does not exist then a new string instance is created and placed in the pool if the string exists then it will not create a new object rather it will return the reference to the same instance. The cache which stores these string instances is known as String Constant pool or String Pool. In earlier versions of Java up to JDK 6 String pool was located inside PermGen(Permanent Generation) space. But in JDK 7 it is moved to the main heap area.
Why did the String pool move from PermGen to normal heap area?
PermGen space is limited space, the default size is just 64 MB. And it was a problem of creating and storing too many string objects in PermGen space. That’s why the String pool is moved to a larger heap area. To make the java more memory efficient the concept of string literal is used.
By the use of ‘new’ keyword, the JVM will create a new string object in the normal heap area even if the same string object present in the string pool.
String a=new String(“Trident”);
Let’s have a look to the concept with a java program and visualize the actual JVM memory Structure:
TAT TAT TAT TAT
The below figure illustrates the storage of String :
Here in the above figure, the String is stored in String constant pool. String object reference variables are stored in the stack area under the method main( ). As main( ) is having some space in the stack area.
- All objects in Java are stored in the heap. The reference variable to the object stored in the stack area or they can be contained in other objects which puts them in the heap area also.
- The string is passed by reference by java.
- A string reference variable is not a reference itself. It is a variable that stores a reference (memory address).
Please Login to comment...