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

JavaObject Oriented ProgrammingProgramming

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.

Example

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);
   }
}

Output

s1 and s2 are string literals:
true
s3 and s4 with new operator:
false
raja
Published on 28-May-2019 13:43:22
Advertisements