Underlying mechanism of String pooling in Java?

后端 未结 7 1725
不知归路
不知归路 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:19

    The following is a slight simplification, so don't try to cite exact details from it, but the general principles apply.

    Each compiled Java class contains a data blob that indicates how many strings were declared in that class file, how long each one is, and the characters that belong in all of them. When the class is loaded, the class loader will create a String[] of suitable size to hold all of the strings defined in that class; for each string, it will then generate a char[] of suitable size, read the appropriate number of characters from the class file into the char[], create a String encapsulating those characters, and store the reference into the class's String[].

    When compiling some class (e.g. Foo), the compiler knows which string literal it encounters first, second, third, fifth, etc. If code says myString = "George"; and George was the sixth string literal, that will appear in code as a "load string literal #6" instruction; the just-at-time compiler, when it is generating code for that instruction, will generate an instruction to fetch the sixth string reference associated with that class.

提交回复
热议问题