String count in the pool with println

后端 未结 2 1079
你的背包
你的背包 2021-01-11 12:01

I am preparing for the OCA SE 7 exam, and some of these questions are really (!) tricky.

In one of the books Im using I found an error I think, so I would like to co

2条回答
  •  佛祖请我去吃肉
    2021-01-11 12:40

    It should be 2 strings: "autumn" and "false". The first is created by the first line. The second is created by the second line because the compiler would optimize it to just:

    System.out.println(false);
    

    which ends up calling PrintStream#print(boolean):

    public void print(boolean b) {
        write(b ? "true" : "false");
    }
    

    This is what happens at runtime, i.e. after the code is executed. However, at the level of the constant pool stored in the bytecode, only 1 string constant is created which is "autumn" in the classfile of the class which contains your main method. You can verify this by running:

    javap -c -verbose ClassName
    

提交回复
热议问题