Why String class is immutable in java?

It is one of the mostly asked question in java interviews.

While making of Java by sun microsystem they have thought that programmers will use mostly String while declaring any variable and assigning its values , making conditions in if-else blocks therefore, they decided to make String constant pool where all the strings get stored in memory (apart from heap memory).

If it would not be immutable:

  1. then redundant String objects could have created in memory which is actually the wastage of memory.
  2. if multiple references are pointing to same string object then if any of the String object changes the values then it could have reflected to others as well.

Therefore, it was mandatory to make String as immutable which means if once the object of string is created then it can not be modified.

Leave a Reply

Your email address will not be published. Required fields are marked *