真是不考不知道

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.


...全文
53 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhaohaoMars 2004-05-12
  • 打赏
  • 举报
回复
搂主不好意思:)
不过现在我还真不太明白你的困惑,期待其他人说明...呵呵
不过我还是觉得我理解了你的意思了啊,呵呵
我的msn:zhaohao2107@hotmail.com

maowu 2004-05-12
  • 打赏
  • 举报
回复
Strings are immutable objects 我清楚得很.
至于你说的什么reference,内存地址这些东西我如果都搞不清楚
也就不必去考什么认证了.
你根本不明白我得疑惑.
zhaohaoMars 2004-05-12
  • 打赏
  • 举报
回复
说的专业点就是Strings are immutable objects!!!
也就是我上面说的意思
zhaohaoMars 2004-05-12
  • 打赏
  • 举报
回复
这是最基础的东西,建议回去把reference理解一下,呵呵
s1,s2都reference内存中的同一块地址
s3是new了一个String,所以他在内存中新开辟了一个地址,
所以s1==s2,当然也就s1.equals(s2)。
而s1!=s3(因为指向的不是同一块内存地址空间),但是s3.equals(s1)(因为值相同),OVER!
happyhzic 2004-05-11
  • 打赏
  • 举报
回复
就是说用String s = "xxxxx"
这样生成的String没有重复的

50,523

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧