What exactly does immutable mean – that is, what are the consequences of an object being mutable or immutable? In particular, why are Java’s Strings immutable?
My understanding is that the StringBuilder type is something like a mutable equivalent to String. When would I use StringBuilder rather than String, and vice-versa?
Immutable means that once the constructor for an object has completed execution that instance can’t be altered.
This is useful as it means you can pass references to the object around, without worrying that someone else is going to change its contents. Especially when dealing with concurrency, there are no locking issues with objects that never change
e.g.
Foodoesn’t have to worry that the caller togetValue()might change the text in the string.If you imagine a similar class to
Foo, but with aStringBuilderrather than aStringas a member, you can see that a caller togetValue()would be able to alter theStringBuilderattribute of aFooinstance.Also beware of the different kinds of immutability you might find: Eric Lippert wrote a blog article about this. Basically you can have objects whose interface is immutable but behind the scenes actual mutables private state (and therefore can’t be shared safely between threads).