We know in Java Strings are stored in the heap memory area. Inside this heap memory, there is a specific memory area called String Pool. When we create string primitives, that will be stored in the string pool memory area thanks to the java string's immutability.
Refer to the following code.
public class StringPoolDemo{
public static void main(String[] args){
String a = "hello";
String b = "hello";
}
}
Both a, and b string primitives are the same. So without creating two string objects in a heap, JVM can create only one string and connect both reference variables to the same string object. When this happens, string objects will be created inside the special memory area called the heap's string pool.
This string pool is a big hash map. All the strings will be stored as elements of the hash map.
But the story is slightly different when it comes to creating strings using the constructor. Because at that time, the string will behave as an object rather than a primitive. So string object will be created inside the heap. Not in the string pool.
Also, we can add strings into the string pool memory area manually using the String.intern() function.
public class StringPoolDemo{
public static void main(String[] args){
String s = "hello world";
s.intern();
}
}
When running this code s will be stored inside the string pool memory.
Let's write some code to test this out.
public class StringPoolDemo{
public static void main(String[] args){
String a = "hello";
String b = "hello";
System.out.println(a.equals(b)); // true
System.out.println(a == b); // true
}
}
In both outputs, we get true as the output. So we can say that both a and b reference to the same string object.
You can use -XX:+PrintStringTableStatistics JVM flag to see how many buckets are available in your JVM string pool and how many of them are used.
If your application has a huge number of string primitives, you can gain considerable efficiency by increasing the string pool size using -XX: StringTableSize=.
Make sure to use a prime number as the value for best performance.
Top comments (1)
Very interesting!