Why String is Immutable in Java
Join the DZone community and get the full member experience.
Join For Freethis is an old yet still popular question. there are multiple reasons that string is designed to be immutable in java. a good answer depends on good understanding of memory, synchronization, data structures, etc. in the following, i will summarize some answers.
1. requirement of string pool
string pool (string intern pool) is a special storage area in java heap. when a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.
the following code will create only one string object in the heap.
string string1 = "abcd"; string string2 = "abcd";
if string is not immutable, changing the string with one reference will lead to the wrong value for the other references.
2. allow string to cache its hashcode
the hashcode of string is frequently used in java. for example, in a hashmap. being immutable guarantees that hashcode will always the same, so that it can be cashed without worrying the changes.that means, there is no need to calculate hashcode every time it is used. this is more efficient.
3. security
string is widely used as parameter for many java classes, e.g. network connection, opening files, etc. were string not immutable, a connection or file would be changed and lead to serious security threat. the method thought it was connecting to one machine, but was not. mutable strings could cause security problem in reflection too, as the parameters are strings.
here is a code example:
boolean connect(string s){ if (!issecure(s)) { throw new securityexception(); } //here will cause problem, if s is changed before this by using other references. causeproblem(s); }
in summary, the reasons include design, efficiency, and security. actually, this is also true for many other “why” questions in a java interview.
Published at DZone with permission of Ryan Wang. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments