字符串拼接在以下代码中是如何工作的?

huangapple go评论80阅读模式
英文:

How is String concatenation working in following

问题

根据以下Stack Overflow讨论,代码如下:

String a = "hello world!";
String b = "hello" + " world!";
boolean compare = (a == b);

compare 应该为 true,这是正确的。然而,我有以下代码:

String s1 = "This is";
String s2 = " a new String";
String s3 = s1 + s2;
String s4 = "This is a new String";

在比较 System.out.printf("s3 == s4:%s\n", s3 == s4);//always false 时,结果总是 false。我的理解是,在将 s1s2 连接起来时,s3 会在池中创建一个字符串,当创建 s4 时,它会指向相同的池位置。但事实并非如此。我已经尝试过不同的 JDK 版本,包括 7、8 和 14,结果是一致的。

英文:

As per the following <https://stackoverflow.com/questions/44037516/how-java-string-pool-works-when-string-concatenation> conversation,

String a = &quot;hello world!&quot;;
String b = &quot;hello&quot; + &quot; world!&quot;;
boolean compare = (a == b);

The compare should be true which is correct.
However, I've the following code

String s1 = &quot;This is&quot;;
String s2 = &quot; a new String&quot;;
String s3 = s1 + s2;
String s4 = &quot;This is a new String&quot;;

On comparing System.out.printf(&quot;s3 == s4:%s\n&quot;, s3 == s4);//always false
It is always false. My understanding is that on concatenation of s1 & s2, s3 will create a string in pool and when s4 is created it will point to the same pool location. But this is not the case. I've tried this with different JDKs including 7, 8 and 14 and the results are consistent.

答案1

得分: 3

以下是您要翻译的内容:

这是Java语言规范中关于池化字符串行为的规定(重点是我的):

3.10.5 字符串字面值

[...]

此外,字符串字面值始终引用相同的String类实例。这是因为字符串字面值 - 或者更一般地说,作为常量表达式值的字符串(§15.28节) - 被“interned”以共享唯一实例,使用String.intern方法。

只有类型为String常量表达式会被池化。"这是一个新字符串""hello" + " world!"是常量表达式。编译器可以在编译时评估这些表达式。s1 + s2不是常量表达式。

因此,在执行s1 + s2时,将创建一个新字符串。但请注意,另一个字符串恰好具有与新字符串相同的字符,因为您使用字符串字面值初始化了s4

英文:

This is how the behaviour regarding pooling strings is specified in the Java Language Specification (emphasis mine):

> 3.10.5 String Literals
>
> [...]
>
> Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

Only constant expressions of type String are pooled. &quot;This is a new String&quot;, and &quot;hello&quot; + &quot; world!&quot; are constant expressions. The compiler can evaluate these expressions at compile time. s1 + s2 is not a constant expression.

So when executing s1 + s2, a new string is created. But note that another string, which just so happens to have the same characters as the new string, is in the string pool, because you used a string literal to initialise s4.

huangapple
  • 本文由 发表于 2020年5月4日 17:06:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/61588647.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定