I have known that JVM maintains a string literal pool to increase performance and maintain JVM memory and learned that string literal is maintained in the string pool. But I want to clarify something related to the string pool and string object created on the heap.
Please correct me if my explanation is wrong.
String s = "abc";
If the above line is executed, "abc" string literal is added to the string pool if it does not exist in the pool. And string object is created on the heap and a reference s will point to the literal in the pool.
Questions:
Does this code create string object on the heap every time it is executed?
Does string literal pool maintain only string literals or does it maintain string object as well?
When does JVM decide that it needs to add string literal to the string pool? does it decide in the compile time or runtime?
I am not sure where exactly string object is created if it points to a string literal in the pool.
Thanks.
解决方案
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.