带有println的池中的字符串计数 [英] String count in the pool with println

查看:92
本文介绍了带有println的池中的字符串计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为OCA SE 7考试做准备,其中一些问题确实(!)很棘手。

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 confirm the following please...

public static void main(String... args) {
    String autumn = new String("autumn");      // line one
    System.out.println("autumn" == "summer");  // line two
}

println 方法执行,池中有多少 String 对象?

After the println method executes, how many String objects are there in the pool?

我的理解是:
- 第一行不会将字符串添加到池中
- 第二行创建autumn和summer并将它们添加到池中
所以书中的正确答案是2 。

It is my understanding that: - line one does not add the string to the pool - line two creates "autumn" and "summer" and adds them to the pool So the correct answer in the book is 2.

然而,我也认为......因为我应该对考试问题感到偏执...同样也会创建字符串false并添加到池...所以我认为3应该是正确的答案......或者其他一些黑魔法是否会发生......真实和假已经被JVM默认放入池中了什么? 。

However, I also think... since Im supposed to be paranoid with the exam questions... that also the string "false" is created and added to the pool... So I think 3 should be the correct answer... or does some other black magic happen like... "true" and "false" are already put into the pool by the JVM by default or something?...

有人可以确认吗?

编辑:
经过一些研究后我发现在书中谈到错误并不公平;作为一般提示:考试题目通常根据以下代码制定;所以他们显然对简单的计算代码本身在本地做什么的简单计算感兴趣。因此范围不允许检查 println(boolean b)实现或编译器优化。足够公平:))

after some research I find that it was not fair of me to speak of an 'error' in the book; as a general tip: exam questions are usually formulated in terms of 'the following code'; so they are clearly interested in plain old simple calculation of what the code itself is locally doing. So the scope therefore does not allow inspection of the println(boolean b) implementation or compiler optimizations. Fair enough :)

推荐答案

它应该是2个字符串:autumnfalse。第一个是由第一行创建的。第二行是由第二行创建的,因为编译器会将其优化为:

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);

最终调用 PrintStream #print(boolean)

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

这是在运行时发生的事情,即之后代码被执行。但是,在字节码中存储的常量池级别,仅创建1个字符串常量,即autumn 在包含 main 方法的类的类文件中。您可以通过运行来验证这一点:

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

这篇关于带有println的池中的字符串计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆