我有个问题。例子:public class Test { public static void main(String[] args){ String a = "hello"; String b = a; a = "bye"; System.out.println(b); //Output: "hello" }}为什么?“a”在内存中与“b”不在同一个空间?谢谢您的帮助。
2 回答
拉莫斯之舞
TA贡献1820条经验 获得超10个赞
String a = "hello"; // a is a reference to the "hello" string object
String b = a; // b is a reference to the same "hello" string object
a = "bye"; // a is updated to reference the "bye" string object
// b is still referencing the "hello" string object
System.out.println(b); // "hello" is printed
哆啦的时光机
TA贡献1779条经验 获得超6个赞
当你写
String b = a;
你不是在说“b
现在和永远更多地指向与”相同的东西a
。
相反,您是在说“将a
的值分配给b
”。在进行新的赋值之前,a
和b
都将指向同一个对象,但是一旦你赋值a
或b
一个新值,这将不再为真。
添加回答
举报
0/150
提交
取消