How and where does String literals in Java stored in the memory?


Strings are used to store a sequence of characters in Java, they are treated as objects. The String class of the java.lang package represents a String.

You can create a String either by using the new keyword (like any other object) or, by assigning value to the literal (like any other primitive datatype).

Example

public class StringDemo {
   public static void main(String args[]) {
      String stringObject = new String("Hello how are you");
      System.out.println(stringObject);
      String stringLiteral = "Welcome to Tutorialspoint";
      System.out.println(stringLiteral);
   }
}

Output

Hello how are you
Welcome to Tutorialspoint

Storage of Strings

Strings are stored on the heap area in a separate memory location known as String Constant pool. String constant pool: It is a separate block of memory where all the String variables are held.

When you store a String as

String str1 = "Hello";

directly, then JVM creates a String object with the given value in a String constant pool.

And whenever we try to create another String as

String str2 = "Hello";

JVM verifies weather any String object with the same value exists in the String constant pool, if so, instead of creating a new object JVM assigns the reference of existing object to the new variable.

And when we store String as

String str = new String("Hello");

using the new keyword, a new object with the given value is created irrespective of the contents of the String constant pool.

Updated on: 02-Jul-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements