Wednesday, January 19, 2011

Why String is Immutable?

After hearing a lot of discussions regarding immutability of String class, I have decided to write this post. This is a common question asked in interviews.

Before talking about immutability of string, I would like to discuss generically about immutable objects.

Immutable Objects are those objects whose state can not be changed after construction.

Properties of immutable objects are as follows:Class should be final (to ensure it can't be overridden)
  • Data members (fields) should be private and final
  • Class should not provide any mutator method which can change the state of any data member

  • Thread safety (we need not to take care of synchronization issues)
  • Need not to provide copy constructor, clone method
  • Need not to be defensively copied as you can not change state after construction
  • Good to be used as keys for Map or Set as you can not change the state

Looking into string Class
String is final, doesn't provide any mutator and data members are private and final thus it is immutable.

Philosophy behind making could be:
  • String is extensively used in any java application and passed across methods, you need not to worry if some one can change your object,
  • In multi-threaded application you need not to worry about synchronization
  • String is heavily used as key to maps and sets you will get same hash code as its state can not be changed
  • Apart from this the immutable String class ensures that
    security-sensitive APIs only have to check the file name or host name
    once, and can then rely on it to stay the same as you can not change the same object.
Apart from String, other immutable classes are Integer, Float etc. all Wrapper classes.

No comments: