Immutable Objects and Strings in Java
March 20, 2013 Leave a comment
Why are Strings made immutable?
Security Reasons: as strings are used in class loaders, if it is made mutable it could lead to a potential security threat.
Efficient Memory Usage: We use string for whole lot of reasons with the concept of ‘literal pool/string pool’, when string literal is recreated it points to the already existing literal instead of creating new string in the pool memory.
Note: Along with Strings all the wrappers of primitive data types are made immutable.
Whys is String made final?
In order not to override the existing String class to remove immutable property where we would lose the above mentioned advantages it is made final.
Disadvantages of Strings being immutable?
And the negative side of immutable strings is that even a small change to a big string could lead to the construction of entire string again which is both time and space inefficient. In these scenarios we should go for StringBuffer/StringBuilder.
String pool memory and garbage collection:
These two concepts are contradictory in the sense, intention of coming up with pool concept is for the memory efficiency and for this reason GC wont act on it.
Since string pool memory does not come under the scanner of JAVA’s Garbage Collector (GC); once a string literal is put into pool memory it never dies. The inference from this is NEVER EVER store any user sensitive or confidential information in strings because a hacker can always dump the heap which would give away all the secure information.
String used as hashmap keys because of their immutable property:
Hashmap’s key constraint is that once after inserting key-value pair into it, one should not change the key value (with which hashcode is tied up with) as we manipulate the correct bucket based on the hascode which in turn is associated to the key value. And hence after inserting the key-value pair if one changes the key value, its hashcode changes and hence lookup of this pair ends up in returning null. Because of String’s immutable property one can safely make use of String as key in hashmaps.
Recent Comments