[英]String immutability, pop quiz
There are a lot of questions concerning String immutability, but yet I haven't found an answer for why the following happens: 关于字符串不可变性有很多问题,但是我还没有找到以下原因的答案:
1) "TEST".equals("TEST") // TRUE obviously
2) "TEST" == "TEST" // Also TRUE since String's are immutable
3) "TEST" == "T" + "E" + "S" + "T" // TRUE, but why? Due to compiler optimalization?
4) "TEST" == new String("TEST"); // FALSE, because you explicitly request a new String?
Can anyone correct me if necessary and explain in further detail 3 and 4? 如有必要,谁能纠正我并进一步详细解释3和4? Many thanks! 非常感谢!
The concatenation happens at compile time, so the String goes to the pool, that's why you get true
. 串联发生在编译时,因此String进入了池,这就是为什么得到true
的原因。
Regarding the last one, a new object is created because your'e using new
keyword and comparing the references by ==
, so you're getting false
. 关于最后一个,创建了一个新对象,因为您使用的是new
关键字,并通过==
比较引用,因此您将得到false
。
And this has nothing to do with immutability. 这与不变性无关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.