r/programming • u/jonjonbee • Jun 05 '18
Code golfing challenge leads to discovery of string concatenation bug in JDK 9+ compiler
https://stackoverflow.com/questions/50683786/why-does-arrayin-i-give-different-results-in-java-8-and-java-10
2.2k
Upvotes
View all comments
Show parent comment
5
u/adrianmonk Jun 05 '18
It is still immutable. The confusion is probably that Java variables never, ever contain objects. They only contain references to objects.
Thus a variable declaration
String sdoes not create an immutable variable; it creates a mutable variable. The value of the variable will be a reference (to aStringobject). The variable is mutable because it can be changed to a different reference.The object is immutable because the
Stringclass does not provide any way of changing aStringobject after it is created. There are no methods to add, remove, or take away characters.When you write
s += "hi", what happens is:Stringobject.schanges value. Its old value is a reference to oneString, and its new value is a reference to a different (new)String.