Java new String and new StringBuilder in heap behavior

后端 未结 2 1552
再見小時候
再見小時候 2020-12-11 14:08
  1. Does the String pool reside on the heap? If yes, are String literals eligible for garbage collection?

When using new String(\"abc\"), we kn

2条回答
  •  一整个雨季
    2020-12-11 14:43

    You are confusing compile time, load time, and runtime.

    A string literal is added to the constant pool at class loading time. Just a mention of a literal anywhere in the class code is enough; you don't even have to execute any line of code in that class.

    On the other hand, the expression new String("literal") yields a new String instance each time it is evaluated. That instance is distinct from the one in the constant pool and has a copy of the string value.

    StringBuilder acts exactly the same way as String in this respect: it is initialized with a copy of the string literal's value.

提交回复
热议问题