Underlying mechanism of String pooling in Java?

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

    The Java compiler has special support for string literals. Suppose it did not, then it would be really cumbersome to create strings in your source code, you'd have to write something like:

    // Suppose that we would not have string literals like "hi"
    String s = new String(new char[]{ 'h', 'i' });
    

    To answer your questions:

    1. More or less, and if you really want to know the details, you'd have to study the source code of the JVM, which you can find at OpenJDK, but be warned that it's huge and complicated.

    2. No, those two are not equivalent. In the first case you are explicitly creating a new String object:

      String s=new String("Test");
      

      which will contain a copy of the String object represented by the literal "Test". Note that it is never a good idea to write new String("some literal") in Java - strings are immutable, and it is never necessary to make a copy of a string literal.

    3. There's no way I know of to check what's in the string pool.

提交回复
热议问题