String Pool in Java is a special storage space in Java Heap memory where string literals are stored. It is also known as String Constant Pool or String Intern Pool.
Whenever a string literal is created, the JVM first checks the String Constant Pool before creating a new String object corresponding to it.
The String Pool is empty by default, and it is maintained privately by the String class.
When we create a string literal, the JVM first checks that literal in the String Constant Pool. If the literal is already present in the pool, its reference is stored in the variable.
However, if the string literal is not found, the JVM creates a new string object in the String Constant Pool and returns its reference.
Need of String Constant Pool:
When we create a String object, it uses some amount of space in the heap memory.
Let's say we are creating n number of String objects with the same value, and distinct memory is allocated to each of these string objects (though they all contain the same string).It uses lots of heap memory. So in order to reduce memory usage, JVM optimizes the way in which strings are stored with the help of a string constant pool.
Way to create string and its effect on string pool
1. String literal
Ex. String str=”hello”;
String str1=”hello”;
String str2=”welcome”;
Changes in the String Pool:
By default, String Pool is empty. When the compiler executes the first line, it creates a string literal "hello" in the String Constant Pool.
When the compiler executes the second line, it first checks the String Constant Pool. Since the string literal "hello" is already present in the String Pool, its reference is stored in str1.
As a result of the execution of the third statement, a new string literal "welcome" is created in the String Constant Pool (since it is not already present). Its reference is stored in str2.
2. Using new keyword
We can create new String objects using the new keyword. When we create new string literals using the new keyword, memory is allocated to those String objects in the Java heap memory outside the String Pool.
Ex. - String str=”hello”;
String str1=new String(“hello”);
Changes in the Java heap memory:
The first string gets stored in the String Constant Pool, but the second string object gets stored out of the string pool in the Java heap memory.
3. Using String.intern() method
Ex. -String str = "Java";
String str1 = new String("hello").intern();
String str2 = new String("welcome");
str2.intern();
The first statement creates a new string literal in the String Constant Pool.
The second variable str1 holds a reference to the already existing "hello" literal in the String Constant Pool.
The third statement creates a new string literal in the String Pool as "welcome" is not initially present.
留言