String Constant Pool in Java
Last Updated :
22 Jul, 2024
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. 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");
}
}
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");
}
}
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:
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:
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:
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:
Similar Reads
String Class in Java
A string is a sequence of characters. In Java, objects of the String class are immutable, which means they cannot be changed once created. In this article, we are going to learn about the String class in Java.Example of String Class in Java:Java// Java Program to Create a String import java.io.*; cl
7 min read
Interning of String in Java
String Interning in Java is a process of storing only one copy of each distinct String value, which must be immutable. Applying String.intern() on a couple of strings will ensure that all strings having the same contents that shares the same memory.Example:When a string is created using a string lit
4 min read
Hashtable toString() Method in Java
The toString() method in the Hashtable class in Java returns a string representation of the key-value mappings contained in the hashtable. The string is in the form of a comma-separated list of key-value pairs enclosed in curly braces. The toString() method is inherited from the java.util.Hashtable
2 min read
String Arrays in Java
A String Array in Java is an array that stores string values. The string is nothing but an object representing a sequence of char values. Strings are immutable in Java, this means their values cannot be modified once created.When we create an array of type String in Java, it is called a String Array
5 min read
Compare two Strings in Java
String in Java are immutable sequences of characters. Comparing strings is the most common task in different scenarios such as input validation or searching algorithms. In this article, we will learn multiple ways to compare two strings in Java with simple examples.Example:To compare two strings in
4 min read
Storage of String in Java
In Java, we know both Stack and Heap space are part of Java Virtual Machine (JVM). However, these memory spaces are used for different purposes. Stack space contains specific values that are short-lived whereas Heap space is by Java Runtime to allocate memory to objects and JRE classes. In Java, str
3 min read
CopyOnWriteArrayList toString() method in Java
The toString() method of CopyOnWriteArrayList returns the string representation of the list. Syntax: public String toString() Parameters: The function does not accepts any parameter. Return Value: The function returns the string representation of the list. Below programs illustrate the above functio
1 min read
StringBuffer Class in Java
The StringBuffer class in Java represents a sequence of characters that can be modified, which means we can change the content of the StringBuffer without creating a new object every time. It represents a mutable sequence of characters.Features of StringBuffer ClassThe key features of StringBuffer c
11 min read
Java Strings Coding Practice Problems
Strings are a fundamental part of Java programming, used for handling and manipulating textual data efficiently. This collection of Java string practice problems covers key operations such as finding string length, slicing, case conversion, palindrome checking, anagram detection, and pattern matchin
2 min read
StringBuilder capacity() Method in Java
In Java, the capacity() method of StringBuilder Class is used to return the current capacity of StringBuilder object. The capacity is the amount of storage available to insert new characters.Example 1: Here, we use the capacity() method to check the current capacity of the StringBuilder object.Java/
2 min read