In Java, string pool is a reserved memory for caching string literals to reduce the cost of allocating a new string. It is located in the main part of the Java heap memory (aka the young and old generations) since Java 7+; in the permanent generation (aka PermGen) of the Java heap memory before Java 7

How the string pool works

String literals and interning

String literals are added or reused if existing from the string pool

@Test
public void testStringLiterals() {  
    // This string is created and stored in the string pool
    String s1 = "Hello Koding";

    // This string is reused from the string pool
    String s2 = "Hello Koding";

    assertThat(s1).isSameAs(s2);
}

The process of caching string literals into the pool is called interning

String objects

String objects created by new operator are stored in heap memory

@Test
public void testStringObjects() {  
    // This string is created and stored in heap memory
    String s1 = new String("Hello Koding");

    // This string is created and stored in heap memory
    String s2 = new String("Hello Koding");

    assertThat(s1).isNotSameAs(s2);
}

We should not use new operator to create a new string in practice, the example is only for demonstration

String object vs String literal

A string object has a different memory location with a string literal although they have the same value

@Test
public void testStringLiteralVsObject() {  
    // This string is created and stored in heap memory
    String s1 = new String("Hello Koding");

    // This string is created and stored in the string pool
    String s2 = "Hello Koding";

    assertThat(s1).isNotSameAs(s2);
}

Interning a string object

Using String's intern() method to add a string into the pool, if not existing, and get the reference address in the pool

@Test
public void testStringIntern() {  
    String s1 = new String("Hello Koding");
    s1 = s1.intern();

    String s2 = "Hello Koding";

    assertThat(s1).isSameAs(s2);
}

Conclusion

In this tutorial, we learned about the string pool, how it works and explored the difference between string literals and string objects. You can find below all usage test cases