It might sound strange at first, might seem simple, yet I'm stuck the well-expected point. I think in following code, text
is referenced to by s
and t
, as output,I would get hello world hello world
, but not. I get 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);
}
}
What point did I miss until now? I'm really baffled at that. Presumably a new object is created there implicitly. But why?
Following one is not related Java, but C-knowers. I try to interpret the above code in C. I get expected result there, 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;
}