Search code examples
javastringliteralspool

Java String Literal Pool


Let's say we have the following code

String x = new String("xyz");
String y = "abc";
x = x + y;

A friend of mine says that 4 objects are created in total, where I say that only 3 are created. Can someone explain what's going on in the background? I've read about String Literal Pool, but I can find an answer for this.

My explanation for the creation of the 3 object is as follows: one in the String Literal Pool at compile time ("abc"), and two at runtime on the heap ("abc" and x + y)


Solution

  • 4 objects are created as follow

    // 1. "xyz" in the literal pool
    // 2. a new String object which is a different object than "xyz" in the pool
    String x = new String("xyz");
    
    // 3. "abc" in the literal pool
    String y = "abc";
    
    // 4. new String object
    x = x + y;