Java变量引用

标签 java

如果这个问题真的很愚蠢,我很抱歉,但我想知道是否有人可以告诉我为什么会发生这种情况:

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/

相关文章:

java - 无法将textView文本从MainActivity(第一个 Activity )传递到UserprofileActivity(第二个 Activity )

java - Seam 安全性和 Prettyfaces 登录后重定向到错误的 URL

java - 如何删除实体和子实体

剩余大量内存时出现 java.lang.OutOfMemoryError (94GB/200GB Xmx)

Java BitSets 写入文件

java - API每次响应不同的JSON类型

java - 签名 jar 的 AspectJ 加载时编织

Java-在游戏中保存分数

java - Hibernate ConstraintViolationException 可能是由于循环方案

Java的SWT : Setting the size of Group hides its widgets