真是不考不知道
maowu 2004-05-11 05:37:59 有些东西一直都想当然的原来是错的,诸位看看这道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.