Underlying mechanism of String pooling in Java?

后端 未结 7 1715
不知归路
不知归路 2020-12-15 18:09

I was curious as to why Strings can be created without a call to new String(), as the API mentions it is an Object of class java

7条回答
  •  春和景丽
    2020-12-15 18:15

    1. A kind of, but not exactly.
      String constants are created and interned during constant pool resolution. This happens upon the first execution of LDC bytecode that loads a string literal. After the first execution the JVM replaces JVM_CONSTANT_UnresolvedString constant pool tag with JVM_CONSTANT_String tag so that the next time LDC will take an existing string instead of creating a new one.

    2. No. The first use of "Test" will create a new string object. Then new String("Test") will create the second object.

    3. Yes, using HotSpot Serviceability Agent. Here is an example.

提交回复
热议问题