DEV Community

Anushka Kawale
Anushka Kawale

Posted on

Java String Immutability & SCP behavior

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";
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode


What happens internally ?

  • "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";
Enter fullscreen mode Exit fullscreen mode

Only ONE Object is created in SCP.
Both s1 and s2 point to the same object.

s1 ─┐
    ├──► "Java"  (SCP)
s2 ─┘

Enter fullscreen mode Exit fullscreen mode

What If We Use new ?

String s3 = new String("Java");
Enter fullscreen mode Exit fullscreen mode

Java is stored in SCP.
A new Object is created in heap.
s3 points to heap object.

So now two objects exist :

  1. SCP object
  2. 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)