Originally posted by Arnb Sen:
This is getting confusing.. My original question was about Immutable / Mutable. And as mentioned - Strings are immutable!
So if I have a piece of code
"s" has changed. Right ? So how are strings immutable ?
I see this problem often, and it is typically the result of:
a) the lack of distinction between references and objects
b) the inability to efficiently talk about objects because they have no name
c) the loose definition of "immutable"
These points are related. In your case, "s" is a String reference that refers to some (unnamed) object. It is the object that is immutable, not the reference (since as you have observed, you can reassign it). One way to talk about the object is "the object that s refers to". You'll find that you cannot (within some specific bounds) change the state of that object. This digresses to the definition of "immutable", since as a client of the object, you never know (or care) about its state. What you might about, however, is the idempotence of its "contract" (its API). For example, given the String object "xyz", the charAt contractual operation (API method) is idempotent - that is, it will consistently return the same value upon consecutive calls.
It is generally accepted (either inadvertantly or not), that if a class' operations (methods) are all idempotent, that the type is "immutable". This holds for java.lang.String.
Also, see if this helps
http://jqa.tmorris.net/GetQAndA.action?qids=75&showAnswers=true