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:
- then redundant String objects could have created in memory which is actually the wastage of memory.
- 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.