生活在同一个记忆空间

我有个问题。


例子:


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”不在同一个空间?


谢谢您的帮助。


慕雪6442864
浏览 166回答 2
2回答

拉莫斯之舞

String a = "hello"; // a is a reference to the "hello" string objectString b = a; // b is a reference to the same "hello" string objecta = "bye"; // a is updated to reference the "bye" string object           // b is still referencing the "hello" string objectSystem.out.println(b); // "hello" is printed

哆啦的时光机

当你写String b = a;你不是在说“b现在和永远更多地指向与”相同的东西a。相反,您是在说“将a的值分配给b”。在进行新的赋值之前,a和b都将指向同一个对象,但是一旦你赋值a或b一个新值,这将不再为真。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java