Java – String Literal and String constant pool concept

In previous article, we have seen ways to create String and short introduction to String Literal pool concepts

This article will elaborate more on String Literal pool concept and will dive into why such thing is required in Java?

Before that, we will understand few things about String objects,

  • String created using new operator/keyword is stored/placed inside heap memory
  • Every string created stored separately inside heap memory, even if 2 or more string created with the same value
  • Creating string using new keyword, perfectly fits into pure OO principle
  • String stored/placed inside heap memory is also referred as non-pool area

String Literal:

  • The other way to create String in Java is using double quotes (“) as shown in below example,
String str = “Bench Resources”;
  • When we create string using above method/way, compiler internally perform string object creation task with the string literal provided within double quotes and stores inside string literal area
3-String-constant-literal-pool-concepts

As you can see from above figure, there are 2 areas to store strings in Java,

  1. Heap memory –> area where other Java objects is stored
  2. String pool –> to store string literals

Note: String literal pool area is actually a special area inside heap memory

Q) How String Literals are stored/placed inside String constant pool area ?

  • We will create 3 string literals to understand working
// declaration of string literals
String str1 = “Hello”;
String str2 = “World”;
String str3 = “Hello”;

// string operation to concatenate 2 strings
str1.concat(str2);
4-String-constant-literal-pool-concepts-a

Explanation:

The working,

  • When we created 1st string str1 = “Hello”; –> compiler checks string pool area and finds no equivalent string therefore creates a new string literal
  • Again, 2nd string str2 = “World” is created –> similarly compiler checks and finds no equivalent string therefore creates a new string literal
  • Next time 3rd string str3 = “Hello” is created –> this time compiler checks and find an equivalent string therefore doesn’t creates any new string instead a reference is assigned to str3
  • This way, string pool consists of only unique strings
  • The last concatenation operation –> concatenates the 2 strings i.e.; str1 and str2 using String class’s concat() method
  • A new string “HelloWorld” is created, but this is not assigned

As soon as, we will change the last concatenation statement as below,

// string operation to concatenate 2 strings and assignment
str4 = str1.concat(str2);

Now, string str4 points to concatenated string “HelloWorld”

Note: String pool is also alternatively referred as String Constant pool or String Literal pool

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - String comparison with example
Java - String class with example