Member-only story
What is String Constant Pool in Java? | Explained with Examples
Learn what the String Constant Pool is in Java, how it optimizes memory, and why String literals are stored differently than objects. Includes code examples and explanations.
Introduction
If you’re learning Java, you’ve probably used String
values like this:
String name = "Ramesh";
But did you know this string is stored differently than using new String("Ramesh")
?
This is because of something called the String Constant Pool.
In this article, we’ll explore:
- What the String Constant Pool is
- Why Java uses it
- How it improves memory usage
- Key examples and interview tips
📌 What is the String Constant Pool?
In Java, the String Constant Pool (also called the String Intern Pool) is a special memory area in the Java Heap that stores string literals.
✅ Simply put:
It’s a memory optimization technique that avoids creating duplicate
String
objects with the same value.
🔍 How It Works
When you create a string like this:
String str1 = "Java";
➡️ Java stores "Java"
in the String Pool. If you later write:
String str2 = "Java";
➡️ Java doesn’t create a new object — it simply points str2
to the same "Java"
instance in the pool.
But if you do:
String str3 = new String("Java");
➡️ It creates a new object in the heap, even if "Java"
already exists in the pool.
✅ Why Does Java Do This?
- Strings are immutable, meaning they can’t be changed once created.
- Many programs use the same string values repeatedly (like
"yes"
,"no"
,"OK"
). - So instead of creating multiple
"yes"
strings, Java reuses the same one in the pool, saving memory.