“String Pool” in Java…

Kalana Sudesh Gunaweera
3 min readSep 14, 2023

In this article, I’ll explore what the String Pool is, how it works, and why it matters for memory optimization in your Java programs.String pool is the specific memory area in the java heap memory where the JVM store the String objects. It is also known as the String Constant Pool or String Intern Pool.

String s1 = "hello";
String s2 = "hello";

System.out.println(s1 == s2); // true

// The two strings s1 and s2 are references to the same object in the string pool

These strings are unique, which means there are no duplicates allowed in the pool. When you create a string literal in your Java code, the JVM checks if an identical string already exists in the pool. If it does, the reference to the existing string is returned. If not, a new string is created in the pool, and its reference is returned.

Why Does the String Pool Matter?

  1. Memory Efficiency: By reusing identical strings in the String Pool, Java reduces memory overhead.
  2. Performance: String interning (the process of adding a string to the String Pool) allows for faster string comparisons. Instead of comparing individual characters, the JVM can compare string references, making operations like equality checks more efficient.
  3. String Immutability: The String class in Java is immutable, which means once a string is created, it cannot be changed. This property allows strings to be safely shared without the risk of unintended modifications.

When Strings are Not in the String Pool?

Not all strings are automatically placed in the String pool. Strings created using the new keyword are not added to the pool.

String customString = new String("Hello, World!");

In this case, customString will not be part of the String pool, even though its content is the same as the earlier example. It's essential to be aware of this distinction when working with strings in Java.However, we can stop this kind of memory allocation to String objects using the String.intern() method in Java.

When you use the String.intern() method on a String object, it checks if an equivalent String exists in the pool. If found, it returns a reference to that String; otherwise, it adds the String to the pool and returns a reference to the newly added String. This method allows you to explicitly add Strings to the pool.

String str = "Java";

String str1 = new String("Java").intern();

String str2 = new String("Code");
str2.intern();

The first statement creates a new string literal in the String Constant Pool. The second variable str1 holds a reference of the already existing “Java” literal in the String Constant Pool. The third statement creates a new string literal in the String Pool as “Code” is not initially present.

References:

--

--

Kalana Sudesh Gunaweera

Software Engineer | Full Stack Developer | Graduated from University of Moratuwa - Sri Lanka | AMIE (SL) | AEng.(ECSL)