Blogger

Delete comment from: Javarevisited

Niraj Singh said...

Main Reason of String being immutable is performance. Before you guys tear my opinion to shreds please read ahead :-).

Strings are backbone of Java or for that matter any other programming language. As we have seen thousand examples in this great blog itself, for example classloaders uses classname to load a class which is a string, usernames, passwords, database connection names etc. all are stored as string.

Now lets assume for a second that String were not immutable what would happen? String references pointing to litrals in constant pool would keep on changing the contents there hence a havoc would occur.

To fix this java designers would have to remove the constant pool all together. Thus we would have to create a new instance of string all the time which would go into the heaps. Tons of string would result in out of memory errors hence impact the performance of all the java applications.

Jan 22, 2013, 9:08:53 AM


Posted to Why String is Immutable or Final in Java? Explained

Google apps
Main menu