Java String literal pool and string object

There is no “literal pool”. Interned Strings are just normal heap objects. They may end up in the PermGen, but even then, they could eventually be garbage-collected.

The class file has a constant pool, which contains the String literals used in the class. When the class is loaded, String objects are created from that data, which is probably very similar to what String#intern does.

Does this code create string object on the heap every time it is executed?

No. There will be one String object that is being reused. It has been created when the class was loaded.

Does string literal pool maintain only string literals or does it maintain string object as well?

You can intern Strings as well. I assume that they are treated more or less the same.

When does JVM decide that it needs to add string literal to the string pool? does it decide in the compile time or runtime?

Literals are always “pooled”. Other Strings need to have “intern” called on them. So in a way, the decision is made at compile-time.

Leave a Comment