×

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

Exception Handling Program in Java

Exception Handling Program in Java Exception means something that is abnormal. In Java, an exception is treated as a problem that disrupts the normal flow of the program. An exception leads...

7 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.

Sparse Numbers in Java

In this section, we will be very well acknowledged about the sparse numbers in Java, how a number can be verified if it is a sparse number or not. Sparse Numbers Any...

3 minutes read.

How to create a mirror image of a 2D array in Java

Problem Statement We have provided a list of m x n. here m indicates rows, and n indicates columns). Printing the fresh matrices should result in a mirror reflection of an...

2 minutes read.

Print Pencil Shape Pattern in Java

Another pattern made from asterisk symbols that use loops and other logical concepts is the pencil pattern. It is usually requested to draw a pattern using a program. To write the...

6 minutes read.

Brilliant Number in Java

It is a number N that is made up of two prime numbers that have the same number of digits and is called a brilliant number. Several/Some of the brilliant Numbers...

3 minutes read.

Java String Matches vs Contains

String Matches in Java The matches() function and its variations are used to determine whether or not a provided text matches a regular expression. The functioning as well as output of...

3 minutes read.

Java Characters

Normally, when we work with characters, we use primitive data types char. When we have to work with the objects of char, we use Character class. Character class has many important...

2 minutes read.

Minimum Lights to Activate Java Snippet Class

Minimum Lights to Activate Problem in Java In prison, there is a hallway that is N units long. Given an N-dimensional array A. If the light at the ith position is...

3 minutes read.

Java copy constructor Example

Java provides the copy constructor much like C++ does. However, it is produced by default in C++. While we define our own copy constructor in Java. With an example, we will...

3 minutes read.

Java Strictfp Keyword

Strictfp is used to impose limits on floating-point calculation. It ensures that we will get the same result on every platform while performing an operation with the floating-point variable. The floating-point calculation is platform-dependent due...

1 minute read.

Java DatagramSocket and Java DatagramPacket

Datagrams TCP/IP style networking specifies a serialized, predictable, and reliable stream of data in the form of a packet. Servers and clients communicate through a reliable channel, such as TCP socket, have a dedicated...

6 minutes read.

How to Convert Timestamp to Date in Java

How to Convert Timestamp to Date in Java You can convert Timestamp to Date by using the constructor of Date class. It returns the long millisecond from Epoch (1st January 1970)...

2 minutes read.

Java copy file

There are for the most part 3 methods for duplicating documents utilizing java language. They are as given underneath: Utilizing File StreamUtilizing FileChannel ClassUtilizing Files class. 1. Using File Stream: Here we are...

5 minutes read.

How Many Ways to Create Objects in Java

Introduction Java comes under the category of object-oriented programming languages. Since it is object-oriented, everything in Java is considered an object. Java is a diverse programming language that is designed to...

6 minutes read.

Java Generate Random String

Java Generate Random String In this tutorial, we will learn about to generate random string in Java. Random generation strings mean any string will be generated, which does not follow any...

7 minutes read.

XNOR operator in Java

The opposite of the binary equivalent of XOR is given by XNOR. Truth table: XYXNOR001010100111 If the bits are the same, it returns 1, else it returns 0. Examples:  Input: 10 20 Output : 1 A Binary...

3 minutes read.

Lambda expressions in Java

A brief introduction to Lambda expression in java In this topic, we will discuss the lambda expression in java. A lambda expression in Java is an enhanced version of an anonymous...

13 minutes read.

Java Math signum() Method

The signum() method of Java Math class returns the signum function of the value. Syntax: public static double signum(double d)public static float signum (float d) Parameters: The parameter ‘d’ represents the floating-point value whose...

2 minutes read.

Java HashSet

HashSet implements the set interface. It uses the hash table to make the collection to store different data types. The hash set is the unordered collection of different data types....

6 minutes read.