Last Updated:

What is a string pool in Java?

In the diagram below, we can see exactly how the string pool is located in the Java Heap memory. And how different ways of creating strings affect how they are placed in memory.

string pool in Java

The string pool itself is only possible because strings in Java are immutable. Also, the string pool allows you to save memory in the Java Runtime, although this requires more time to create the string itself.

Example of working with a row pool

When we use double quotation marks to create a new string, the first step is to look for a string with the same value in the string pool. If java finds such a string, it returns a reference, otherwise a new row is created in the pool, and then the reference is returned.

However, using the operator causes the String class to create a new String object. We can then use the method to place this object in a row pool or access another object from the string pool that has the same intern()

The following is a program that demonstrates how to work with a row pool:

The result of the program:

What is happening inside our program is clearly visible in the diagram above.