In Java, String is a non - primitive data type.
String is a sequence of characters / an array of characters.
It belongs to the java.lang package and represents sequence of characters.
String name = "Anushka";
String is an object. It is immutable. Stored in special memory called "String Pool".
Why String is Immutable ?
Once created, a String object cannot be changed.
String s = new String("Hello");
s.concat("World");
- "Hello" remains unchanged.
- " World" is checked in SCP (created if not present).
- A new object "Hello World" is created in heap.
What is String Constant Pool (SCP) ?
A String Constant Pool is a special memory area inside the Heap where Java stores string literals.
It is used to :
- Avoid duplicate objects.
- Save memory.
- Improve performance.
String s1 = "Java";
String s2 = "Java";
Only ONE Object is created in SCP.
Both s1 and s2 point to the same object.
s1 ─┐
├──► "Java" (SCP)
s2 ─┘
What If We Use new ?
String s3 = new String("Java");
Java is stored in SCP.
A new Object is created in heap.
s3 points to heap object.
So now two objects exist :
- SCP object
- Heap object
Why SCP exists ?
- Every string literal would create new object.
- Huge memory waste.
- Performance issues. SCP makes Java memory efficient.

Top comments (0)