ashokgelal ashokgelal - 2 years ago 71
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

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

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

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

Answer Source

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


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download