Strings are indeed immutable, but "s" is not a String - it is a reference to a String object. As such, it can point to different objects over time. 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).
Just to add on top of what Ulf has said and if you were intended to ask, how come the value being pointed by S is changing -- as Ulf told, "s" is not an object here but a reference to a string object.
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.
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
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.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
I agree on the use of this keyword. If a variable or parameter is not meant to be changed, declare it final. Any issue raised by the compiler due to this is a signal worth looking into, because the code is obviously doing something you didn't expect or something you forgot you intended.