Friday, November 21, 2014

Need for Immutable String in Java

While understanding String Immutability there were some answered questions as to why the designers of Java made String Immutable. We checked that String is immutable but Why so?

Well, it's difficult to go inside the brain of designers of java but based on the usage as of today we can speculate as to what would have been going on in their brain while making java immutable.

1. Easy storage and housekeeping
Strings are used a lot inside a program. A lot of Strings are repeated. For example in a College Database application, same names (Strings) are repeated again and again. Hence it makes better sense to keep a single copy of all strings at a single place (String Pool). Instead of creating new objects again and again. Garbage Collection and Storage of these high volume data becomes easy.



2. Hashcode does not change
Since Strings are immutable, their hascode won't change like other objects. Thus Strings do not calculate hashcode every time we call hashcode function, Hascode us kept cached. Since Strings are used a keys in HashMaps and other such Structures, we save a lot of time but not calculating hashcode every time we need to retrieve an Object.

3. Network Security
All passwords we enter online are strings. Bank details are passed as Strings. If they are mutable, anyone could change them over the network, which would wreak havoc. Same goes with classnames while loading a Class. 

4. Prevents Concurrency Issues
Since Strings are immutable, hence no need to synchronize. Hence no concurrency issues while using Strings.

No comments:

Post a Comment