Underlying mechanism of String pooling in Java?

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

    That's not tightly related to the subject, but whenever you have doubts as to what will java compiler do, you can use the

    javap -c CompiledClassName
    

    to print what is actually going on. (CompiledClassName from the dir where CompiledClassName.class is)

    To add to Jesper's answer, there are more mechanisms at work, like when you concatenate a String from literals or final variables, it will still use the intern pool:

    String s0 = "te" + "st";
    String s1 = "test";
    final String s2 = "te";
    String s3 = s2 + "st";
    System.out.println(s0==s1); //true
    System.out.println(s3==s1); //true
    

    But when you concatenate using non-final variables it will not use the pool:

    String s0 = "te";
    String s1 = s0 + "st";
    String s2 = "test";
    System.out.println(s1 == s2); //false
    

提交回复
热议问题