×

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

Arithmetic exception in Java

Exception Handling is one of the most potent ways of handling runtime faults and preserving the application's normal flow. In Java, an exception is an out-of-the-ordinary state, and exceptions are...

3 minutes read.

Command Class in Java

We use the command class to run commands against the database. The Command class may find a set of parameter objects for use in sending values to a stored procedure...

3 minutes read.

How Many Ways to Create an Object in Java?

As you know, a class is a blueprint for an object, and you can create objects from it. There are several ways to create objects of classes in Java. This...

6 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 Identifiers

In Java, the symbolic notations used for identification are called identifiers. Identifiers can be the name for the class, variable name declaration, name of the package, constant name and many...

3 minutes read.

What is interpreter in Java?

The programming language Java is platform-neutral. Therefore, can use Java on any platform that supports the Java processor. The Piece of software transforms the Java bytecode contained in the class...

5 minutes read.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

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

Java Integer doubleValue() method

The doubleValue() method of Integer class returns a double value for this Integer after a widening primitive conversion. Syntax public double doubleValue() Parameters NA Specified by This method is specified by doubleValue in class Number Return Value This...

1 minute read.

String Declaration in Java

A string is a group of characters. In Java, the string can be treated as both class and datatype. In Java programming, the String class have many advantages. Everything in...

3 minutes read.

Special Operators in Java

An operator in Java is a special symbol. It is used to perform operations on two or more variables.  We all know basic operations in Java. There are 8 types...

5 minutes read.

Java Protected Keyword

An access modifier is a keyword that Java protects. It can be used to constructors, methods, inner classes, and variables. Variables, methods, and constructors that have been marked protected in...

3 minutes read.

Java Integer compareUnsigned() method

The compareUnsigned() method of Integer class compares two int objects numerically by treating the values as unsigned. Syntax public static int compareUnsigned(int x , int y) Parameters The parameters ‘x’ and ‘y’ represent the...

1 minute read.

Java Char Keyword

The java char keyword is a data type which is defined as character data type.Char keyword belongs to a primitive data type where the data types are classified into primitive...

4 minutes read.

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.

How to Convert Date to Timestamp in Java

How to Convert Date to Timestamp in Java You can convert Date to Timestamp by using the getTime() method of Date class. It returns the long millisecond from Epoch which can...

1 minute read.

Console Errors in Java

An unlawful motion taken through the person that reasons this system to act abnormally is amistake until this system is compiled or run; maximum programming mistakes pass unnoticed.The software is...

3 minutes read.

How to Convert long to String in Java

How to Convert long to String in java It is used if we have to display a long number in the text field because everything is displayed as a String. A...

3 minutes read.

Program to Find Square Root of a Number Without sqrt Method in Java

The Java Math class sqrt () function can be used to determine the square root of a number. In this section, we'll write a Java program to find a number's...

3 minutes read.

Java Math tanh() Method

The tanh() method of Java Math class returns the hyperbolic tangent of the specified double value. Syntax: public static double tanh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic tangent is to...

2 minutes read.