关于java String文字池和String的连接的混淆 [英] a confusion about java String literal pool and String's concatenation

查看:70
本文介绍了关于java String文字池和String的连接的混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全部,
我在编写下面的代码时遇到问题

all, i faced a problem when a write the code below

String hello = "Hello";
String str5 = "Hel" + "lo";
String str8 = "Hel";
String str9 = "lo";
String str10 = str8 + str9;
System.out.println("str10==hello?" + (str10 == hello)); 
System.out.println("str5==hello?" + (str5 == hello));
System.out.println("str10==str5?" + (str10 == str5));

然后我运行我的代码并且控制台打印此

then i run my code and the console print this

str10 == hello ? false
str5 == hello ? true
str10 == str5 ? false

这让我很困惑。为什么第二次打印TRUE但第一次打印FALSE ??
在我理解String文字池时,当一个字符串被定义并且JVM将检查池是否包含该字符串时,如果没有,则将该字符串放入池中。
在我的代码中,变量 hello 存在于字符串池中, Helo lo 也在池中,我的问题是

this confused me a lot. why the second print TRUE but the first print FALSE?? in my comprehension of String literal pool,when a string defined and JVM will check if the pool contains that string,if not ,put the string into the pool.
in my code,variable hello exists in string pool,"Helo" and "lo" also in the pool,my question is


  1. 如果池中存在串联 Helo lo 的结果。

  2. 关于str5和str10s的定义有什么区别,为什么它们不是==? str5和str10是指字符串池中不同的 Hello 吗?(==似乎表示引用是同一个对象)

  1. if the result of the concatenation of "Helo" and "lo" exists in the pool.
  2. what's the difference between the definition about str5 and str10s',and why they are not "=="? does str5 and str10 refer to the diffrent "Hello" that in the string pool?("==" seems to mean the reference is the same object)

我的jdk版本:1.6.0_29

我的IDE:Intellij Idea 11.2

my jdk version :1.6.0_29
my IDE:Intellij Idea 11.2

任何人都可以指出它出来了吗?非常感谢

anyone can point it out? thank you very much

推荐答案

它的行为应该如此。它在JLS的两个部分中得到了解决。

It behaves as it should. It is adressed in two sections of the JLS.

JLS#3.10.5


作为常量表达式值的字符串(§15.28) - interned以便使用String.intern方法共享唯一的实例。

strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

JLS#15.28 列出了被视为常量表达式的内容。特别是,字符串文字是常量表达式(Hel 和lo)但是要将变量视为常量,它必须是最终的。

JLS #15.28 lists what is considered as a constant expression. In particular, string literals are constant expressions ("Hel" and "lo") but for a variable to be considered a constant, it needs to be final.

在您的情况下,如果您稍微更改代码以使 str8 str9 常数,您将获得 true 三次:

In your case, if you change your code slightly to make str8 and str9 constant, you will get true three times:

final String str8 = "Hel";
final String str9 = "lo";

这篇关于关于java String文字池和String的连接的混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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