Java 生活在同一个记忆空间里
我有个问题 例如:Java 生活在同一个记忆空间里,java,Java,我有个问题 例如: 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”在内存中的位置不一样吗 谢谢你的帮助。
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”在内存中的位置不一样吗
谢谢你的帮助。当你写信时
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
你不是说“b
现在和永远都会指向与a
相同的东西”
相反,您说的是“将
a
的值分配给b
”。在进行新赋值之前,a
和b
都将指向同一个对象,但只要您赋值a
或b
一个新值,这将不再是真值。您赋值b=a
,因此它们都指向同一个对象。然后你分配了a=
其他的东西,所以它们现在是不同的对象。这个问题的状态是什么?你已经得到了答案;应将其标记为已解决。
String b = a;