Wednesday, August 24, 2011

Why Strings in Java are immutable?

Strings in Java are immutable. But why?

We all know that strings are immutable in java. But ever thought why? This question popped up in my mind and I did some research to come to a conclusion. Here is what explains the immutability of Strings -

1) Same object need not to be created again and again. Example - Database connection details used in various places. Also, string pool gets created in PERM area of Java Heap , so if there are too many String there is good chance of OutOfMemoryError .

2) Since String is immutable it can safely shared between many threads ,which is very important for multithreaded programming and to avoid any synchronization issues in Java.

3) Being immutable String in Java caches its hashcode and do not calculate every time we call hashcode method of String, which makes it very fast as hashmap key to be used inhashmap in Java

4) It is used by the class loading mechanism. Had String been mutable, a request to load "" could have been changed to load ""

1 comment: