Why String literal is stored in String Constant Pool in Java?

There are two ways to create a String object in Java

  • By using the new operator

String str = new String("Tutorials Point");
  • By using String literal

String str = "Tutorials Point";

Whenever we call new String() in Java, it will create an object in the heap memory and String literals will go into String Constant Pool (SCP).

For objects, JVM used SCP which is for efficient memory management in Java. Unlike other Java objects, instead of managing String object on the heap area, they introduced the String constant pool. One of important characteristic of String constant pool is that it does not create the same String object if there is already String constant in the pool.


public class SCPDemo {
   public static void main (String args[]) {
      String s1 = "Tutorials Point";
      String s2 = "Tutorials Point";
      System.out.println("s1 and s2 are string literals:");
      System.out.println(s1 == s2);
      String s3 = new String("Tutorials Point");
      String s4 = new String("Tutorials Point");
      System.out.println("s3 and s4 with new operator:");
      System.out.println(s3 == s4);


s1 and s2 are string literals:
s3 and s4 with new operator:

Updated on: 17-Nov-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started