一开始听起来可能很奇怪,可能看起来很简单,但我却卡在了预料之中。我认为在下面的代码中,text
被 s
和 t
引用,作为输出,我会得到 hello world hello world
,但不是。我得到 hello world
。
class Test2 {
private volatile static String text = "";
public static void main(String[] args) {
String s = text;
text = "hello world";
String t = text;
System.out.println(s + " " + t);
}
}
到目前为止我错过了什么?我真的很困惑。大概在那里隐式创建了一个新对象。但是为什么?
下面一个不是Java相关的,是C-knowers。我尝试用 C 解释上面的代码。我在那里得到了预期的结果,hello world hello world
。
#include <stdio.h>
int main()
{
char const volatile * volatile x = "";
char const volatile * volatile const * xPtr = &x;
x = "hello world";
char const volatile * volatile const * xPtr2 = &x;
printf("%s %s\n", *xPtr, *xPtr2);
return 0;
}
最佳答案
I get hello world.
你应该在开头有两个空格。
What point did I miss until now?
使用调试器向您展示了原因,但简而言之,您只有 Java 中的引用和原语。没有引用文献。
char const volatile * volatile const * xPtr = &x;
Java 中没有这样的东西。
Presumably a new object is created there implicitly.
一个新的 StringBuilder
和一个新的 char[]
是隐式创建的,但我认为这不是你的意思。
单步执行代码
String s = text; // text = "", s = ""
text = "hello world"; // text = "hello world", s = ""
String t = text; // text & t = "hello world", s = ""
System.out.println(s + " " + t);
关于java - String = 运算符引用或在这种情况下创建新的 String 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51176173/