真是不考不知道

maowu maowu 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
有些东西一直都想当然的原来是错的,诸位看看这道scjp模拟体:
Which of the following lines will print false?
1. public class MyClass
2. {
3. static String s1 = "I am unique!";
4. public static void main(String args[])
5. {
6. String s2 = "I am unique!";
7. String s3 = new String(s1);
8. System.out.println(s1 == s2);
9. System.out.println(s1.equals(s2));
10. System.out.println(s3 == s1);
11. System.out.println(s3.equals(s1));
12. }
13. }


A. line 8
B. line 9
C. line 10
D. line 11
E. none of these

我一直以为是A, C,
原来 (s1 == s2)是true

详细解析:
C is correct. Line 10 will print false. Strings are immutable objects. That is, a string is read only once the string has been created and initialized, and Java optimizes handling of string literals; only one anonymous string object is shared by all string literals with the same contents. Hence in the above code the strings s1 and s2 refer to the same anonymous string object, initialized with the character string: "I am unique!". Thus s1 == s2 will return true and obviously s1.equals(s2) will return true. But creating string objects using the constructor String(String s) creates a new string, hence s3 == s1 will return false even though s3.equals(s1) will return true because s1 and s3 are referring to two different string objects whose contents are same.


...全文

相关推荐

评论 5
收藏 已收藏
分享
返回顶部
maowu
Java 51,407 成员 86,128 内容