×

String Pool in Java

String Pool in Java: String is one of the most important discussed topics in Java. There are a lot of concepts related to the String and one of them is String pool in Java. In this section, we will discuss the two important concepts of String i.e. String pool or String Intern concept. The string pool in Java imitates the Flyweight design pattern.

What is a String Pool?

It is a well-known fact that a string is treated as an object in Java. In Java, a string object is always stored in the heap memory. When we create string, the JVM automatically creates a pool in the heap memory to store the string literals is called String pool. The Java String class takes care of the String pool, and by default, the String pool is empty. String Intern pool or String Constant pool are the other synonyms of the Java String pool.

The Need of String Pool

It is an obvious question that why the String pool is required when there is already a heap memory? The answer is, as the object allocation is always costly work in Java, as it enhances the time and space complexity. Therefore, the JVM (Java Virtual Machine) does the optimization from their end to reduce the time and space complexity. To achieve the same, an area inside the heap area is marked as the String pool.

Each and every time when a string literal is created in a Java program, the JVM checks in the String pool whether the string literal, which is going to be created, is present in the String pool or not. If the string literal is already present, the JVM returns the reference of that string literal; otherwise, it allocates the memory for the string literal inside the String pool. Thus, we can say that the String pool only contains the distinct string literals.

String Creation in Java

Following are the ways to create strings in Java.

By using String Literal

 // memory is allocated in the String pool
String st1 = “Tutorial & Example”;
String st2 = “Tutorial & Example”;
String st3 = “tutorial & example”; 

Let’s observe the Java program of the string literals.

FileName: StrPoolExample.java

 public class StrPoolExample
{ 
// main method
public static void main(String argvs[])
{
// Input string literals
String st1 = "Tutorial & Example";
String st2 = "Tutorial & Example";
String st3 = "tutorial & example";
// if-else blocks checking for the same references
if(st1 == st2)
{
System.out.println("Strings st1 and st2 have the same reference.");
}
else
{
System.out.println("Strings st1 and st2 do not have the same reference.");   
}
if(st1 == st3)
{
System.out.println("Strings st1 and st3 have the same reference.");
}
else
{
System.out.println("Strings st1 and st3 do not have the same reference.");
}
}
} 

Output:

 Strings st1 and st2 have the same reference.
Strings st1 and st3 do not have the same reference. 

Explanation: Before the start of the program, the String pool remains empty. So, for str1, the JVM allocates memory in the String pool. However, for st2, the JVM checks for the presence of the string literal “Tutorial & Example”. As the string literal is already present, the JVM does not allocate new memory for st2 and returns the reference of the already created string literal. Therefore, st1 and st2 have the same reference. Because of the case sensitivity feature of the Java language, the string literal of st3 is different from the st2 or st1. Hence, a new object is created for the reference variable st3. The following diagram depicts the same.

String Pool in Java

By using the new Keyword

 // memory is allocated in the heap
String st1 = new String(“Tutorial & Example”);
String st2 = new String(“Tutorial & Example”);
String st3 = new String(“tutorial & example”); 

Now, observe the program for the same.

FileName: StrPoolExample1.java

 public class StrPoolExample1
{ 
// main method
public static void main(String argvs[])
{
// creating string objects using the new keywords
String st1 = new String("Tutorial & Example");
String st2 = new String("Tutorial & Example");
String st3 = new String("tutorial & example");
// if-else blocks checking for the same references
if(st1 == st2)
{
System.out.println("Strings st1 and st2 have the same reference.");
}
else
{
System.out.println("Strings st1 and st2 do not have the same reference.");   
}
if(st1 == st3)
{
System.out.println("Strings st1 and st3 have the same reference.");
}
else
{
System.out.println("Strings st1 and st3 do not have the same reference.");
}
}
} 

Output:

 Strings st1 and st2 do not have the same reference.
Strings st1 and st3 do not have the same reference. 


Explanation: Creation of the string objects using the new keyword always allocated memory outside the string pool. The JVM never checks for the presence of the same strings. Therefore, objects are created for st1, as well as, st2 even though both contain the same string. The reference variable str3 is also treated in the same way. The following diagram represents the same.

String Pool in Java

The intern() method

The intern() method either refers to the already created object in the String pool, or it keeps the strings in the String pool. If the current string object is already present in the String pool, the intern() method returns the reference of it. It is determined by the equals() method. If the equals() method returns true, the reference is returned from the string pool; otherwise, an object is created in the string pool. Note that, even with the new keyword the intern() method puts the string literal in the String pool. Let’s confirm the same with the help of the following Java program.

FileName: StrPoolExample2.java

 public class StrPoolExample2
{ 
// main method
public static void main(String argvs[])
{
// creating string objects using the new keywords
String st1 = new String("Tutorial & Example");
String st2 = new String("Tutorial & Example");
// invoking the intern() method
String st3 = new String("Tutorial & Example").intern();
// creating string objects using the string literal
String st4 = "Tutorial & Example";
// if-else blocks checking for the same references
if(st1 == st2)
{
System.out.println("Strings st1 and st2 have the same reference.");
}
else
{
System.out.println("Strings st1 and st2 do not have the same reference.");   
}
if(st2 == st3)
{
System.out.println("Strings st2 and st3 have the same reference.");
}
else
{
System.out.println("Strings st2 and st3 do not have the same reference.");
}
if(st4 == st3)
{
System.out.println("Strings st1 and st3 have the same reference.");
}
else
{
System.out.println("Strings st1 and st3 do not have the same reference.");
}
}
} 

Output:

 Strings st1 and st2 do not have the same reference.
Strings st2 and st3 do not have the same reference.
Strings st3 and st4 have the same reference. 

Explanation: The first statement in the output is straightforward. Now, observe the second statement in the output. It says, “st2 and st3 do not have the same reference.” The reason behind it is that the calling of the intern() method for the st3. The intern() method puts the string in the String pool, whose reference is held by the st3. The following diagram depicts the same.

String Pool in Java

The third statement of the output shows the same reference because of the same reason. Note that the string st4 holds the reference of the string literal, which is always created in a string pool.

Note: The string literals in Java implicitly invokes the intern() method. Hence, they are always created in the String pool.


Related Topics

Java Queue Interface

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional...

2 minutes read.

Java Generics Questions

Introduction We'll walk through a few real-world examples of interview questions and responses for Java generics in this article. Java 5 saw the debut of the fundamental idea of generics. Due to...

9 minutes read.

Banking Application in Java

JDBC (Java Database Connectivity), which provides an API to connect to, execute, and fetch data from any databases, can be used to handle transactions in Java. There are several factors...

7 minutes read.

Java Full Stack

A person who can create both the front end and back end of an application is a full-stack developer. In essence, the term "Java full-stack" refers to a web developer...

9 minutes read.

Powerful Number in Java

We will define a powerful number in this article and write Java programs to determine whether a given number is a powerful number or not. Java coding interviews and academic...

6 minutes read.

Permutation Coefficient in Java

In this tutorial, we will get familiar with the permutation coefficient in Java.  We will understand it through examples and see different approaches to solving the problem. A permutation is a...

5 minutes read.

Hashtable in Java

Hashtable in Java The Hashtable class implements the Map interface and extends the Dictionary class. It implements a hash table which shows the key-value relation, i.e., it maps the keys to the values....

9 minutes read.

Java Date add Days

In order to operate with the time and the Date in Java, we used the abstract Calendar class. It has several helpful interfaces that enable us to convert dates between...

4 minutes read.

Rotate matrix by 90 degrees in Java | Rotate matrix in Java clockwise and anti-clockwise

In this article, you will be acknowledged about what is a matrix along with an example. Most importantly you will be equipped knowledge on how to rotate the matrix by...

4 minutes read.

Callable Statement in Java

The Callable statement in Java is used to call the functions and Stored procedures. Example: If we want to know about the age of a person based on their date of birth,...

3 minutes read.

Prime Points in Java

The points that divide an integer into two halves containing a prime number are known as prime points. Printing every prime point of a specific number is the task. Let's...

6 minutes read.

String Matches in Java

Firstly we have to know something about String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java...

3 minutes read.

Java Binary Tree

The non-linear data structure known as a binary tree is a type of tree, and because it stores data in a hierarchical manner, it is mostly utilised for finding and...

7 minutes read.

Reverse a String in Java

Reversing a string means that if we have a string called “what is your name”, the reversed format is “eman ruoy si tahw”. Reversing a string involves totally flipping the...

3 minutes read.

Sierpinski Number in Java

The Sierpinski triangle—is it a fractal? The Sierpinski Triangle fractals. A self-similar fractal is the Sierpinski triangle. It is made of an equilateral triangle with its residual area successively reduced by...

3 minutes read.

Java try catch

Java try catch There can be statements that can cause exceptions, and the exception leads to abnormal termination of the program. To avoid that abnormal termination, those statements that look potent...

4 minutes read.

Java Integer rotateLeft() method

The rotateLeft() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value left by the specified number of bits. Syntax public...

1 minute read.

Package naming convention in Java

It is conceivable that many programmers will use the same name for various types, given that Java programmers from all over the world create classes and interfaces. For illustration, suppose...

4 minutes read.

Java Set Interface

We use set when we don't want to allow duplicate entries. All Set implementations do not allow duplicates. HashSet: This class stores its elements in hash tables. It uses the hashCode()...

3 minutes read.

Java Error Stack Trace

The stack trace in Java is an array of stacks.The stack trace reveals the console's location of an exception or error by gathering data from all program methods. The JVM...

3 minutes read.