how is this happening?
we know that string objects are created once and have the same value through their lifetime!!
Once you assign the modified/updated content to the same reference variable "s", the original value is not actually getting modified. Instead a brand new string object is assigned to the same reference variable "s".
In your example itself,
At line 2, the concatenated String "Fred47" is being constructed newly and that is what getting assigned to "s". The original strings "Fred" and "47" are not modified and left as it is.
Originally posted by Ulf Dittmer:
If you want "s" to be immutable, declare it "final" (which you can't do in this case because s is a local variable, but which would be possible if s was an instance variable).
Local variables can be "final", can't they? We don't do it often in Java, but it's legal, I think.
Originally posted by Peter Chase:
We don't do it often in Java, but it's legal, I think.
Well, *we* actually do it often. In fact our team has activated the eclipse setting that automatically declares local variables as final whenever possible (as a save action). It's quite helpful.