字符串串联如何在下面工作 [英] How is String concatenation working in following
问题描述
按照以下> String串联时Java String池如何工作?对话,
String a = "hello world!";
String b = "hello" + " world!";
boolean compare = (a == b);
compare
应该为true,这是正确的.但是,我有以下代码
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";
在比较 System.out.printf("s3 == s4:%s \ n",s3 == s4);//始终为假
这总是错误的.我的理解是,在 s1
& s2
, s3
将在池中创建一个字符串,并且在创建 s4
时将指向相同的池位置.但这种情况并非如此.我已经尝试过使用包括7、8和14在内的其他JDK进行此操作,结果是一致的.
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.
推荐答案
这是在Java语言规范(重点是我的)中指定有关池字符串的行为的方法:
This is how the behaviour regarding pooling strings is specified in the Java Language Specification (emphasis mine):
[...]
此外,字符串文字总是引用类 String
的相同实例.这是因为字符串文字-或更一般地说,是常量表达式值的 字符串 (第15.28节)-是"interned"的.以便使用方法 String.intern
共享唯一的实例.
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
.
仅常量表达式汇集了类型为 String
的a>.这是一个新的字符串"
,以及"hello"+"世界!"
是常量表达式.编译器可以在编译时评估这些表达式. s1 + s2
不是常数表达式.
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.
因此,当执行 s1 + s2
时,会创建一个新的字符串 .但是请注意,另一个字符串恰好与新字符串具有相同的字符,它位于字符串池中,因为您使用了字符串文字来初始化 s4
.
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
.
这篇关于字符串串联如何在下面工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!