The Wayback Machine - https://web.archive.org/web/20240626084940/https://www.geeksforgeeks.org/string-constant-pool-in-java/
Open In App

String Constant Pool in Java

Last Updated : 07 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, Strings are the type of objects that can store the character of values. A string acts the same as an array of characters in Java. Memory allocation is not possible without String Constant Pool. In this article, we will learn about Java String Constant Pool.

What is Java String Pool?

A Java String Pool is a place in heap memory where all the strings defined in the program are stored. A separate place in a stack is there where the variable storing the string is stored. Whenever we create a new string object, JVM checks for the presence of the object in the String pool, If String is available in the pool, the same object reference is shared with the variable, else a new object is created.

Example of Java String Pool

Consider the following two Java programs, the first program produces the output as “Yes”, but the second program produces the output as “No”. Can you guess the reason? 

Example 1:

Java




// Program 1: Comparing two references to objects
// created using literals.
import java.util.*;
  
// Driver Class
class GFG {
    // main function
    public static void main(String[] args)
    {
        String s1 = "abc";
        String s2 = "abc";
  
        // Note that this == compares whether
        // s1 and s2 refer to same object or not
        if (s1 == s2)
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}


Output

Yes

Example 2:

Java




// Program 2: Comparing two references to objects
// created using new operator.
import java.util.*;
  
// Driver Class
class GFG {
    // main function
    public static void main(String[] args)
    {
        String s1 = new String("abc");
        String s2 = new String("abc");
  
        // Note that this == compares whether
        // s1 and s2 refer to same object or not
        if (s1 == s2)
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}


Output

No

Let us understand why we get different outputs with the below explanation. 

The String is a sequence of characters. One of the most important characteristics of a string in Java is that they are immutable. In other words, once created, the internal state of a string remains the same throughout the execution of the program. This immutability is achieved through the use of a special string constant pool in the heap. In this article, we will understand about the storage of the strings. A string constant pool is a separate place in the heap memory where the values of all the strings which are defined in the program are stored. When we declare a string, an object of type String is created in the stack, while an instance with the value of the string is created in the heap. On standard assignment of a value to a string variable, the variable is allocated stack, while the value is stored in the heap in the string constant pool. For example, let’s assign some value to a string str1.

How String Pool Works?

In Java, a string is defined and the value is assigned as:

String str1 = "Hello";

The following illustration explains the memory allocation for the above declaration:

Memory Allocation of String in String Pool

 

In the above scenario, a string object is created in the stack, and the value “Hello” is created and stored in the heap. Since we have normally assigned the value, it is stored in the constant pool area of the heap. A pointer points towards the value stored in the heap from the object in the stack. Now, let’s take the same example with multiple string variables having the same value as follows:

String str1 = "Hello";
String str2 = "Hello";

The following illustration explains the memory allocation for the above declaration: 

Memory Allocation of Two String in String Pool

 

 In this case, both the string objects get created in the stack, but another instance of the value “Hello” is not created in the heap. Instead, the previous instance of “Hello” is re-used. The string constant pool is a small cache that resides within the heap. Java stores all the values inside the string constant pool on direct allocation. This way, if a similar value needs to be accessed again, a new string object created in the stack can reference it directly with the help of a pointer. In other words, the string constant pool exists mainly to reduce memory usage and improve the reuse of existing instances in memory. When a string object is assigned a different value, the new value will be registered in the string constant pool as a separate instance. 

Let’s understand this with the following example:

String str1 = "Hello";
String str2 = "Hello";
String str3 = "Class";

The following illustration explains the memory allocation for the above declaration: 

memory allocation of string in String constant pool

 One way to skip this memory allocation is to use the new keyword while creating a new string object. The ‘new’ keyword forces a new instance to always be created regardless of whether the same value was used previously or not. Using ‘new’ forces the instance to be created in the heap outside the string constant pool which is clear, since caching and re-using of instances isn’t allowed here. 

Let’s understand this with an example:

String str1 = new String("John");
String str2 = new String("Doe");

The following illustration explains the memory allocation for the above declaration:

Example for String Pool

Similar Reads

Java Program for Queries for rotation and Kth character of the given string in constant time
Given a string str, the task is to perform the following type of queries on the given string: (1, K): Left rotate the string by K characters.(2, K): Print the Kth character of the string. Examples: Input: str = "abcdefgh", q[][] = {{1, 2}, {2, 2}, {1, 4}, {2, 7}} Output: d e Query 1: str = "cdefghab" Query 2: 2nd character is d Query 3: str = "ghab
3 min read
Object Pool Design Pattern
Object pool pattern is a software creational design pattern which is used in situations where the cost of initializing a class instance is very high. Basically, an Object pool is a container which contains some amount of objects. So, when an object is taken from the pool, it is not available in the pool until it is put back. Objects in the pool hav
3 min read
Maximum possible cost of buildings with pool view
Consider a series of buildings in a 2-D square plot with different heights and only those buildings are chargeable that have a clear and straight view of the pool from their building. The pool also spans a 2-D square plot with certain coordinates. Given the Coordinates of a square pool, the number of buildings, the charge being paid by customers, a
10 min read
Amazon Interview Experience (Pool campus-2019)
This year Amazon has visited Chandigarh University for pool campus drive. Since there is no restriction on colleges, Nearly 2500-3000 students appeared for the test. Package Offered: CTC: 28.75 Lakhs (Base: 13 LPA  + 1st Year Sign On Bonus: 3, 50, 000 + 2nd Year Sign On Bonus: 2, 25, 000 + Restricted Stock Units vested over 4 years: 10 Lakhs (5%+5%
3 min read
Queries for rotation and Kth character of the given string in constant time
Given a string str, the task is to perform the following type of queries on the given string: (1, K): Left rotate the string by K characters.(2, K): Print the Kth character of the string. Examples: Input: str = "abcdefgh", q[][] = {{1, 2}, {2, 2}, {1, 4}, {2, 7}} Output: d e Query 1: str = "cdefghab" Query 2: 2nd character is d Query 3: str = "ghab
6 min read
C++ Program for Queries for rotation and Kth character of the given string in constant time
Given a string str, the task is to perform the following type of queries on the given string: (1, K): Left rotate the string by K characters.(2, K): Print the Kth character of the string. Examples: Input: str = "abcdefgh", q[][] = {{1, 2}, {2, 2}, {1, 4}, {2, 7}} Output: d e Query 1: str = "cdefghab" Query 2: 2nd character is d Query 3: str = "ghab
3 min read
Python3 Program for Queries for rotation and Kth character of the given string in constant time
Given a string str, the task is to perform the following type of queries on the given string: (1, K): Left rotate the string by K characters.(2, K): Print the Kth character of the string. Examples: Input: str = "abcdefgh", q[][] = {{1, 2}, {2, 2}, {1, 4}, {2, 7}} Output: d e Query 1: str = "cdefghab" Query 2: 2nd character is d Query 3: str = "ghab
2 min read
Javascript Program for Queries for rotation and Kth character of the given string in constant time
Given a string str, the task is to perform the following type of queries on the given string: (1, K): Left rotate the string by K characters.(2, K): Print the Kth character of the string. Examples: Input: str = "abcdefgh", q[][] = {{1, 2}, {2, 2}, {1, 4}, {2, 7}} Output: d e Query 1: str = "cdefghab" Query 2: 2nd character is d Query 3: str = "ghab
2 min read
Sum of all substrings of a string representing a number | Set 2 (Constant Extra Space)
Given a string representing a number, we need to get the sum of all possible sub strings of this string. Examples : Input : s = "6759" Output : 8421 sum = 6 + 7 + 5 + 9 + 67 + 75 + 59 + 675 + 759 + 6759 = 8421 Input : s = "16" Output : 23 sum = 1 + 6 + 16 = 23Recommended PracticeSum of all substrings of a numberTry It! We have discussed a solution
7 min read
Java Program to Access All the Constant Defined in the Enum
An enum is a special class that represents a group of constants. To create an enum, use the enum keyword (instead of class or interface), and separate the constants with a comma. enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; } values() method can be used to return all values present inside enum. We can't see this method
1 min read
Practice Tags :
three90RightbarBannerImg