top

Search

Java Tutorial

.

UpGrad

Java Tutorial

String Pool in Java

What is String Pool in Java?

The String Pool is used to store literal strings. When a string literal is declared in Java code, it is added to the string pool if it is not already present. In Java, the heap memory is where the String Pool is stored in Java.

The string pool in Java is usually used to optimize the memory usage of string objects instead of creating a new object every time a string literal is used. The JVM examines the string pool first to see if the exact string is already there. A reference to the existing string object is returned if it exists. Multiple string literals with the exact value share the same object in the string pool. This eventually boosts performance and also saves space. 

It is to be remembered that only string literals are added to the string pool automatically. Strings created with the “new” keyword are not added to the string pool. They form a new object each time they are created. Additionally, strings created by concatenating other strings are not automatically added to the string pool, although you can add them manually using the “intern()” method.

Creating String in Java

Using String Literal

Let us look at an example of creating a string in Java using a string literal:

String myString = "Hello, UpGrad!";

The string literal "Hello, UpGrad!" is assigned to the “myString” variable in this example. When the Java program runs, the string literal is added to the string pool if it is not there already. A reference to the string object in the pool is also assigned to the “myString” variable.

The string literal is added to the string pool. Therefore, other string literals with the same value will reference the same object in the pool. For instance, if we use the same literal to create another string:

String anotherString = "Hello, UpGrad";

The “anotherString” variable will reference the same object in the string pool as the “myString variable.” This is because they both contain the exact string literal.

It is important to note that if you create a string using the "new" keyword, a "new" string object will be created each time:

String myOtherString = new String("Hello, UpGrad!");

In this case, a new string object is created with the same value as the string literal. However, it is not added to the string pool. If used more often, this can lead to inefficient memory usage and slower performance. Hence, it is generally recommended to use string literals whenever possible.

Using the new Keyword

Here is an example of creating a string in Java using the "new" keyword:

String myString = new String("Hello, UpGrad!");

Let us check out an example of a new String object created from a character array. A string literal cannot be used to do this.

char[] charArray = {'H', 'e', 'l', 'l', 'o', ',', ' ', U', 'p', 'G', 'r', 'a', 'd', ‘!’};

String myString = new String(charArray);

Java String.intern() Method

The “String.intern()” method in Java adds a string to the string pool. It returns a reference to the string object in the pool. However, if the string is already present in the pool, the method returns a reference to the existing object.

Here is a code example of using the “intern()” method to add a string to the string pool:

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

You can also use the “intern() method” on an existing string object to add it to the string pool:

String myString = "Hello, World!";

String internedString = myString.intern();

Memory Allocation in The String Pool

In Java, the JVM takes care of the memory allocation in the string pool is managed by the JVM. Suppose you add a string literal to the string pool. Now the JVM verifies if a similar string object is already in the pool. If there is one, a reference to the existing object is returned. If not, a new string object is created and added to the pool.

The size of the string pool depends on the maximum heap size of the JVM. If the string pool is too large, the JVM may resize the pool or even discard some string objects that are no longer being used. This could be useful to free up memory.

It is important to note that only string literals are automatically added to the string pool. Strings created with the "new" keyword are not added to the string poo. This will create a "new" object each time they are created. Additionally, strings created by concatenating other strings are not automatically added to the string pool. Still, you can add them manually using the “intern()” method.

Here is an example code that demonstrates how memory is allocated in the string pool in Java:

public class StringPoolMemoryAllocationExample {
    public static void main(String[] args) {
        String str1 = "Hello";  // String literal added to the string pool
        String str2 = "World";  // String literal added to the string pool
        String str3 = "Hello";  // Reference to existing string object in the pool
        String str4 = new String("World");  // New string object created in the heap memory
        String str5 = "Hello" + "World";  // Concatenation of two string literals, added to the string pool
        System.out.println(System.identityHashCode(str1)); 
        System.out.println(System.identityHashCode(str2)); 
        System.out.println(System.identityHashCode(str3)); 
        System.out.println(System.identityHashCode(str4)); 
        System.out.println(System.identityHashCode(str5)); 
    }
}

Need of String Constant Pool

The String Constant Pool in Java is needed to optimize memory usage and improve performance by reducing the number of duplicate String objects created in the heap memory. Multiple string literals in Java with the same value will reference the same object in the pool. As a result, this reduces the memory footprint of the program. It also allows for faster String comparisons. This is because instead of comparing the values of each String object, only their memory addresses need to be compared.

The String Constant Pool is also used for interned Strings. These are created by calling the intern() method on a String object. If one exists, this method returns a reference to an equal String object in the pool. This method adds the String to the pool if it does not exist. This returns a reference to the "new" object. This can be useful when many String objects must be compared for equality. In practice, interned Strings can be compared using the “==” operator instead of the equals() method, which can be faster.

Ways to Create Strings

String Literal

There are two ways to create String objects using String literals in Java:

1. Implicit creation: In this method, a String literal is simply assigned to a String reference variable. For instance:

String str = "Hello, UpGrad!";

2. Explicit creation: In the explicit creation method, the "new" operator is used to create a String object using a String literal. For instance:

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

Using New Keyword

There are two ways to create String objects using the "new" keyword in Java:

1. “new String()” constructor: In this method, we use the "new" keyword with the String constructor to create a new String object. For instance:

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

2. “new char[]” constructor: In this method, the "new" keyword is used with the “char[]” constructor to create a "new" character array. This is then used to create a new String object. For instance:

char[] charArray = {'H', 'e', 'l', 'l', 'o', ',', ' ', 'U', 'p', 'G', 'r', 'a', 'd', ‘!’};

String str = new String(charArray);

Using String.intern() Method

The String.intern() method in Java returns a canonical representation of the string object. It checks if a string with the same content is already in the string pool. If it exists, it returns the reference to that string object. If it does not exist, it adds the string to the pool and returns its reference.

There are two ways to create strings using the “String.intern()” method:

1. By calling the “intern()” method on an existing string object:

String str1 = new String("hello");

String str2 = str1.intern();

In this example, the “str1” object is created in the heap memory. The “str2” object is created in the string pool. This is done by calling the “intern()” method on “str1”.

2. By directly creating a string literal:

String str3 = "hello".intern();

In this example, the literal "hello" string is added to the string pool. Its reference is returned by the “intern()” method. The reference is then assigned to the “str3” variable.

String Pool in Java Flow Diagram

Here is a flow diagram that shows how the string pool works in Java, using an example:

1. When the code “String str1 = "Hello";” is executed, the string literal "Hello" is added to the string pool.

2. When the code “String str2 = "Hello";” is executed, Java checks the string pool and finds that "Hello" already exists there. It creates a reference to the existing string object in the pool rather than creating a new one in the heap memory.

3. When the code “String str3 = new String("Hello");” is executed, a new String object is created in the heap memory, even though an identical string already exists in the pool.

4. When the code “String str4 = str3.intern()”; is executed, Java checks the string pool and finds that "Hello" exists. It returns a reference to the existing string object in the pool rather than the new one in the heap memory.

5. When the code “String str5 = "Hel" + "lo";” is executed, the two string literals "Hel" and "lo" are concatenated using the “+” operator. This results in the string "Hello." Java checks the string pool and finds that "Hello" exists. It creates a reference to the existing string object in the pool rather than creating a new one in the heap memory.

When the reference to a string in the pool is no longer used, it becomes eligible for garbage collection. However, the string object itself remains in the pool.

Overall, the string pool in Java allows for efficient use of memory by reusing identical strings rather than creating new ones unnecessarily.

Advantages of String Pool in Java

The String pool in Java has several advantages, including:

  • Memory efficiency: The String pool saves memory and prevents unnecessary object creation by reusing string objects. This can be especially important in applications that frequently use the same string values.

  • Performance: String comparison and lookup operations can be faster using string literals. These are stored in the string pool to be compared by reference rather than value.

  • String immutability: Strings in the String pool are immutable. This means that their values cannot be changed once they are created. This ensures that the values of shared string objects remain consistent and prevents unintentional modification.

  • String interning: The string pool provides a way to intern strings. This can be useful when comparing string objects with different references but the same values.

  • Simplified string handling: The string pool automatically manages string objects. Therefore,  developers do not need to manage string references and object creation manually.

Disadvantages of Using String Objects

The use of string objects in Java provides many benefits. However, there are also some potential disadvantages to be aware of:

  • Memory consumption: Strings are immutable. Hence, a new object is created in memory whenever a modification is made to a string object. This can lead to excessive memory consumption if many string objects are created and manipulated.

  • Security concerns: Sensitive information, such as passwords, cannot be removed from memory once stored as string objects. This is why string is immutable in Java. This could lead to security vulnerabilities.

  • Performance overhead: String objects can be slower to process. They can consume more resources than primitive data types, such as integers or doubles. This can lead to performance issues when dealing with large amounts of data.

  • Object overhead: Every string object has additional overhead beyond its character data. This can add up over time. This can become a problem in applications that create and use large numbers of string objects.

  • Potential for errors: Any time a change is made to a string object, a "new" object is created. This is because strings are immutable. This can lead to errors if developers are not careful in managing references and preventing unintended modifications.

Conclusion

We hope that this tutorial will help beginners get a firm grasp of what string pool in Java is. It is also important to note that one should take formal training in languages like Java if they want to establish themselves in computer science. 

Online learning platforms like upGrad have specially curated courses that deal in Java and various other programming languages. Such courses are beneficial for people who want to take up programming professionally. 

FAQs

1. Can we create a string object without using the string pool?

Yes, we can create a String object using the "new" keyword. This creates a new object in the heap memory rather than using the String pool.

2. Can we disable the Java string pool?

No, we cannot disable the Java string pool. This is because it is an intrinsic part of the JVM. However, we can avoid using string literals. Instead, we can create string objects using the "new" keyword. This can avoid adding them to the pool.

3. Can we add custom objects to the Java string pool?

No, we cannot add custom objects to the Java string pool. The pool is reserved exclusively for immutable string objects.

Leave a Reply

Your email address will not be published. Required fields are marked *