string pool in Java

What is string pool in Java

In Java, the String pool (or String literal pool) is a special area in the JVM (Java Virtual Machine) where String objects are stored. When you create a String object using a string literal (i.e., within double quotes), the JVM checks the String pool first. If the string already exists in the pool, a reference to the existing String object is returned. If not, a new String object is created in the pool, and its reference is returned.

String pooling is done to conserve memory by reusing String objects whenever possible, which is especially useful since strings are immutable in Java (i.e., their values cannot be changed once they are created).

Here’s an example to illustrate how the String pool works:

Example
/*
 * Author: Zameer Ali Mohil
 * */
public class StringPoolExample {
    public static void main(String[] args) {
        String str1 = "hello";
        String str2 = "hello";
        String str3 = new String("hello");

        // true (Both refer to the same String object in the pool)
        System.out.println("str1 == str2: " + (str1 == str2)); 
        // false (str3 is a new String object created in the heap)
        System.out.println("str1 == str3: " + (str1 == str3)); 
        
        // Interning the string creates a reference to the String object in the pool
        str3 = str3.intern();
        // true (After interning, both refer to the same String object in the pool)
        System.out.println("str1 == str3.intern(): " + (str1 == str3)); 
    }
}

In this example:

  • str1 and str2 both refer to the same String object in the String pool because they are created using string literals.
  • str3 is created using the new keyword, so it creates a new String object in the heap memory.
  • By calling intern() on str3, it is interned, meaning a reference to the String object in the pool is returned. After interning, str1 and str3 both refer to the same String object in the pool.

String pooling is particularly useful when you’re dealing with a large number of strings, as it helps conserve memory by reusing common strings instead of creating new objects for every occurrence of the same string value.

Leave a Reply

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