×

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 Xmx

This section will explain what Xmx in Java is and how to establish a Java application's maximum heap size. When we execute a Java application, it occasionally displays an error message...

3 minutes read.

Packages in Java

Packages in Java can be defined as an assortment for grouping various classes and interfaces based on their performance. It is a catalog for holding various java files. They provide...

4 minutes read.

How to Solve the Deprecated Error in Java?

Deprecated Java methods should not be used because they are deprecated (often, there are better, more modern alternatives). API update. Until now, Java has kept everything backward compatible and never...

3 minutes read.

String Concatenation in Java

In Java, it gathers a new String that combines several strings. Following are the manners to concatenate strings in Java: By + (String concatenation) operatorBy concat() method By + (String concatenation) operator Java...

4 minutes read.

How to Run Applet Program in Java

An applet is a new type of program which is put in a webpage. By inserting applet into a webpage dynamic content can be created. Characteristics of an Applet The applet is...

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

Java Heap Space Out of Memory Error

This error is called an "out of memory" error, which indicates that the JVM cannot allocate an object in memory from the heap. Hence the java.lang.out of memory error, describing...

2 minutes read.

Menu Driven Program in Java

Menu Driven Program in Java The menu-driven program in Java is a program that displays a menu and then takes input from the user to choose an option from the displayed...

3 minutes read.

Tetranacci Number in Java

This article mainly describes tetranacci number identification and the Java Program for Tetranacci numbers. Tetranacci number Tetranacci numbers and Fibonacci numbers are related. The key contrast is that a Tetranacci number depends...

3 minutes read.

Converting Long to Date in Java

What Long and Date are in Java and how are they implemented in the Java programming language are the topics of this article. Additionally, we'll go into great detail on...

4 minutes read.

Java String Methods

Java String Methods Java String class is the most important class of the java.lang package. It is used to handle the String related operations. It contains a lot of built-in Java...

2 minutes read.

Ad Hoc Problem on Arrays in Java

Ad hoc problems are issues that arise unexpectedly and require immediate attention. These problems can range from small and straightforward issues to more complex and time-consuming problems. Examples of ad...

3 minutes read.

Java Long Keyword

Long is a primitive data type in Java. To initilize variables, we implement the long keyword. It can also be applied to techniques. A 64-bit two's complement integer can put...

3 minutes read.

Can Abstract Classes have Static Methods in Java

Abstract Class An abstract class in Java is one that explicitly uses the keyword "abstract" in its declaration. There are options for both non-abstract and abstract techniques (method with the body)....

4 minutes read.

What’s New in Java 15

Sealed classes are the new concept that was introduced by Java 15. Sealed classes are a preview feature. Most of the features which are released in java 15 are in...

3 minutes read.

Association in Java

In Java, association refers to the link between two classes established by their objects. One-to-one, one-to-many, and many-to-many connections are managed via association. The Association defines the multiplicity between objects...

5 minutes read.

Java program to print matrix in Z form

In this article, you will be acknowledged about what is a matrix along with an example. Also, most importantly, you will learn how to print matrix in Z form. What is...

5 minutes read.

Model Class in Java

In this section, we will be acknowledged about the model class in Java, its purpose and its uses. Also, we will learn how is this created and leveraged in java. Model...

4 minutes read.

Getting Synchronized Set from Java HashSet

The synchronizedSet() technique for java.util.Collections class is utilized to return a synchronized (string safe) set supported by the predetermined set. To ensure sequential access, it is important that everything admittance...

4 minutes read.

Java Math decrementExact() Method

The decrementExact() method of Math class returns the argument which is decremented by one, throwing an exception is the result overflows an int or long. Syntax: public static int decrementExact (int a) Parameters: The...

1 minute read.