如果这个问题真的很愚蠢,我很抱歉,但我想知道是否有人可以告诉我为什么会发生这种情况:
String helloString = "hello";
String referenceOfHello = helloString;
helloString = "bye";
System.out.println(referenceOfHello);
输出是hello。我原以为会输出“bye”,但那并没有发生。 我知道这是一个非常基本的问题,但我一直认为referenceOfHello存储的是helloString的内存位置,而不是它的值。
谢谢。
最佳答案
代码,注释中有解释。
String helloString = "hello"; //creates variable in heap with mem address 1001
String referenceOfHello = helloString; //now referenceOfHello and helloString are poimnting same object
helloString = "bye"; //now, helloString pointing diff object say 1002, but still, referenceOfHello will point to 1001 object
关于Java变量引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23492662/