英文:
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。我的理解是,在将 s1
和 s2
连接起来时,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 = "hello world!";
String b = "hello" + " world!";
boolean compare = (a == b);
The compare
should be true which is correct.
However, I've the following code
String s1 = "This is";
String s2 = " a new String";
String s3 = s1 + s2;
String s4 = "This is a new String";
On comparing System.out.printf("s3 == s4:%s\n", 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语言规范中关于池化字符串行为的规定(重点是我的):
[...]
此外,字符串字面值始终引用相同的
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. "This is a new String"
, and "hello" + " world!"
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论