There’s plenty of questions about string immutability in Java, for which the author of the question actually re-assigns the reference.
There’s however a remarkable case in which it seems there’s not a re-assignment of the string:
String s = "hello";
s += " world";
You see that as an actual modification of the string. Try it at home.
I’m pretty sure that this is some kind of syntactic sugar, and gets translated by the compiler in something having the same semantics as:
String s = "hello";
s = s + " world";
Can someone confirm this fact?
I can neither confirm nor deny it. If an optimising compiler could prove to itself that no other thread could “see” the initial (pre-
+=) value of s then it would be free to optimise away the concatenation and compile the code to the equivalent ofCompilers have a great deal of freedom as to exactly how they translate from source to bytecode, as long as they obey the memory model.