ashokgelal ashokgelal - 5 months ago 9
Java Question

What is meant by immutable?

This could be the dumbest question ever asked but I think it is a total confusion for a newbie.


  1. Can somebody clarify what is meant by immutable?

  2. Why is a
    String
    immutable?

  3. What are the advantages/disadvantages of immutable objects?

  4. Why should a mutable object such as
    StringBuilder
    be preferred over String and vice-verse?



A nice example (in Java) will be really appreciated.

Answer

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.

class Foo
{
     private final String myvar;

     public Foo(final String initialValue)
     {
         this.myvar = initialValue;
     }

     public String getValue()
     {
         return this.myvar;
     }
}

Foo doesn't have to worry that the caller to getValue() might change the text in the string.

If you imagine a similar class to Foo, but with a StringBuilder rather than a String as a member, you can see that a caller to getValue() would be able to alter the StringBuilder attribute of a Foo instance.

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).