How String Literal Pool Works

There’s only ever be one string with the contents “Hello” in the literal pool. Any code which uses a string constant with the value “Hello” will share a reference to that object. So normally your statement would create one new String object each time it executed. That String constructor will (IIRC) create a copy of the underlying data from the string reference passed into it, so actually by the time the constructor has completed, the two objects will have no references in common. (That’s an implementation detail, admittedly. It makes sense when the string reference you pass in is a view onto a larger char[] – one reason for calling this constructor is to avoid hanging onto a large char[] unnecessarily.)

The string pool is used to reduce the number of objects created due to constant string expressions in code. For example:

String a = "Hello";
String b = "He" + "llo";
String c = new String(a);

boolean ab = a == b; // Guaranteed to be true
boolean ac = a == c; // Guaranteed to be false

So a and b refer to the same string object (from the pool) but c refers to a different object.

Leave a Comment