Table of contents
1.
Introduction
2.
What is Java String Pool?
3.
How String Pool Works?
3.1.
1. Using String Literal
3.2.
2. Using new Keyword
3.3.
3. Using the String.intern() Method
4.
Flow Diagram of String Pool in Java
5.
Example of Java String Pool
5.1.
Java
6.
Advantages of String Pool in Java
7.
Disadvantages of String Pool in Java
8.
Frequently Asked Questions
8.1.
Can strings outside the String Pool be added to it?
8.2.
Does the String Pool affect string comparison in Java?
8.3.
Is the size of the String Pool fixed?
8.4.
Where is string pool stored in JVM?
8.5.
What is the difference between string pool and heap in Java?
9.
Conclusion
Last Updated: Jun 8, 2024
Medium

String Pool in Java

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Java, being one of the most popular programming languages, offers various features that make it unique. One such feature is the Java String Pool, a critical concept for those looking to optimize memory usage in their Java applications. 

String Pool in Java

What is Java String Pool?

Java String Pool is a special storage area in Java Heap memory. It's like a library where Java keeps all the unique string literals used in your program. Think of it like a cache that helps save memory. When you create a string in Java using a string literal, Java first checks the pool. If the string already exists, Java gives you a reference to that existing string. If it's not there, Java adds the new string to the pool and then gives you a reference. This process is known as "interning." The cool part? It's automatic for string literals. This means if you have the same text in different parts of your code, Java will ensure they all point to the same memory location in the pool, making your application more memory-efficient.

How String Pool Works?

The String Pool in Java, also known as the intern pool, operates under the principle of reusing immutable string objects to conserve heap memory. 

Below are the three popular ways of creating strings in Java:

  1. String literal
  2. Using new keyword
  3. Using String.intern() method

1. Using String Literal

String literals are a simple and efficient way to create strings in Java. When a string literal is created, the Java Virtual Machine (JVM) checks a special memory area called the string pool. If the literal already exists in the pool, its reference is returned, avoiding the creation of a new object. This mechanism saves memory by reusing existing string objects.

Syntax

String str = "Hello, World!";

Example

public class Main {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "Hello";
        System.out.println(str1 == str2); // true
    }
}

Explanation

In this example, str1 and str2 are created using string literals. The JVM checks the string pool and finds that the string "Hello" already exists, so both str1 and str2 point to the same memory location. As a result, str1 == str2 returns true.

2. Using new Keyword

Creating strings using the new keyword always generates a new object in the heap memory, regardless of the string's presence in the string pool. This approach ensures that each string object is distinct, even if their contents are identical. It is less memory-efficient compared to string literals.

Syntax

String str = new String("Hello, World!");

Example

public class Main {
    public static void main(String[] args) {
        String str1 = new String("Hello");
        String str2 = new String("Hello");
        System.out.println(str1 == str2); // false
    }
}

Explanation

In this example, str1 and str2 are created using the new keyword, resulting in two distinct string objects in the heap memory. Even though the contents are the same, the references are different, so str1 == str2 returns false.

3. Using the String.intern() Method

The String.intern() method ensures that a string object refers to the canonical representation of the string in the string pool. If the string already exists in the pool, its reference is returned. If not, the string is added to the pool, and the reference to this new string is returned. This method optimizes memory usage by ensuring that strings with identical content share the same memory location.

Syntax

String str = new String("Hello, World!").intern();

Example

public class Main {
    public static void main(String[] args) {
        String str1 = new String("Hello").intern();
        String str2 = "Hello";
        System.out.println(str1 == str2); // true
    }
}

Explanation

In this example, str1 is created using the new keyword and then interned. The intern() method checks the string pool and finds that "Hello" already exists, so it returns the reference from the pool. str2 is a string literal, which also points to the same reference in the pool. Hence, str1 == str2 returns true.

Flow Diagram of String Pool in Java

Below is a simplified flow diagram of how the String Pool works in Java:

  1. Create String Literal: Check if the string literal exists in the pool.
    • Yes: Return the reference to the existing string.
    • No: Add the new string to the pool and return the reference.
  2. Create String with new Keyword:
    • Always create a new string object in the heap.
    • Optional: Call intern() to add the string to the pool if not present and get the reference from the pool.
Flow Diagram of String Pool in Java

Example of Java String Pool

Let's look at a simple example to understand how the Java String Pool works. We'll create a few strings and see how Java handles them in the pool.

  • Java

Java

public class StringPoolExample {

   public static void main(String[] args) {

       // String literals - automatically interned, so these two have the same reference

       String hello1 = "Hello, World!";

       String hello2 = "Hello, World!";

       // Using new keyword - not interned by default, a new object is created

       String hello3 = new String("Hello, World!");


       // Check references

       System.out.println("hello1 == hello2: " + (hello1 == hello2)); // true, because they refer to the same object in the pool

       System.out.println("hello1 == hello3: " + (hello1 == hello3)); // false, because hello3 is not in the pool and refers to a different object


       // Interning hello3

       String hello4 = hello3.intern(); // This moves hello3 to the pool or returns the reference from the pool

       // Check reference after interning

       System.out.println("hello1 == hello4: " + (hello1 == hello4)); // true, now hello4 is in the pool and has the same reference as hello1

   }

}
You can also try this code with Online Java Compiler
Run Code

Output

Output

In this code, hello1 and hello2 are created using string literals that are identical. Due to the String Pool mechanism, both hello1 and hello2 refer to the same object in the pool. Therefore, hello1 == hello2 evaluates to true.

hello3, however, is created using the new keyword, which explicitly creates a new string object outside the pool, even if an identical string already exists in the pool. As a result, hello1 == hello3 evaluates to false.

By calling intern() on hello3, we either add it to the pool or get the reference to the existing identical string in the pool. Since "Hello, World!" already exists in the pool (thanks to hello1 and hello2), hello4 will have the same reference as hello1 and hello2 after interning. Thus, hello1 == hello4 evaluates to true.

Advantages of String Pool in Java

  • Memory Efficiency: Reuses existing string objects, reducing memory footprint.
  • Performance Improvement: Faster string comparison using reference equality (==).
  • Consistency: Ensures consistent string references throughout the application.
  • Immutable Strings: String immutability works well with string pooling for security and simplicity.

Disadvantages of String Pool in Java

  • Memory Overhead: Constantly adding strings to the pool can increase memory usage.
  • Garbage Collection Impact: Strings in the pool are not garbage collected until the JVM is shut down, potentially leading to memory leaks.
  • Thread Safety Concerns: Concurrent access to the string pool may require synchronization, affecting performance.

Frequently Asked Questions

Can strings outside the String Pool be added to it?

Yes, strings created with new String() can be added to the String Pool using the intern() method. This method ensures that a single instance of each distinct string value is maintained in the pool, potentially saving memory.

Does the String Pool affect string comparison in Java?

Indeed, it does. When comparing strings using the == operator, it checks for reference equality. Strings that refer to the same location in the String Pool are considered equal with ==, while equals() should be used for content comparison, especially for strings created with new String().

Is the size of the String Pool fixed?

The size of the String Pool is not fixed and can grow dynamically. However, the amount of memory allocated to the pool can be adjusted with JVM options, allowing for some degree of control over the pool's memory footprint.

Where is string pool stored in JVM?

The string pool is stored in the method area of the JVM, specifically in a part of the memory called the runtime constant pool. This area is used for storing interned strings and other constants.

What is the difference between string pool and heap in Java?

The string pool is a special memory area within the method area used for storing interned strings to save memory. In contrast, the heap is a larger memory area where all Java objects, including strings created with the new keyword, are allocated.

Conclusion

The Java String Pool is a fundamental aspect of Java memory management, optimizing the use of strings, which are among the most commonly used objects in programming. By understanding and utilizing the String Pool effectively, developers can enhance the efficiency and performance of their Java applications. The concept of string interning, coupled with the immutability of strings, ensures a more memory-efficient approach to handling string literals and reduces the overall memory footprint of Java applications. As you continue to develop your Java coding skills, keeping these nuances in mind will help you write more optimized and effective code.

You can refer to our guided paths on the Code360. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass