String count in the pool with println

帅比萌擦擦* 提交于 2019-12-01 03:01:12

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

true and false are not String objects, so they do not count. Even though the exam questions are supposed to be tricky, it's goal is to check the understanding of general concepts. Which is in this case: during class loading (before running), the string literals are loaded to the constant pool. So "autumn" and "summer" will be in the constant pool.

It is described here nicely: http://www.javaranch.com/journal/200409/ScjpTipLine-StringsLiterally.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!