真是不考不知道
有些东西一直都想当然的原来是错的,诸位看看这道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.
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.
...全文
相关推荐
想考中央圣马丁不费事你需要知道以下4点.doc.pdf
想考中央圣马丁不费事你需要知道以下4点.doc.pdf
计算机二级考试报完名就没事了下面这些不知道你考不了.docx
计算机二级考试报完名就没事了下面这些不知道你考不了.docx
2023年计算机二级考试报完名就没事了下面这些不知道你考不了.docx
2023年计算机二级考试报完名就没事了下面这些不知道你考不了.docx
软考高级架构师超详细备考路线,帮助你一次性通过软考!
软考高级架构师超详细备考路线,帮助你一次性通过软考!适用于需要准备软考但不知道从何开始入手的小伙伴们~
软考中级数据库系统工程师备考资料——xmind思维导图(配合第四版教程)
上一篇博客距今已经有20天了,最近在备考5月的软考中级《数据库系统工程师》。咱也不知道为啥我一个做前端的要去考数据库,可能是自己比较喜欢数据库这个玩意儿吧( $ _


