Why String is
immutable in Java?
String is immutable for several
reasons, here is a summary:
·
Security: Parameters are typically represented as String in network
connections, database connection urls, usernames/passwords etc. If it were
mutable, these parameters could be easily changed.
·
String pool : If String weren’t immutable , then we never had String
pool great feature in String class. Let say :
String
a=“Paras”;
String
b=“Paras”
We
all know that a and b points to same Object in heap, if a changed to ”Chawla”, b
will still point to “Paras” which is not possible if String weren’t immutable.
String a="Paras";
String b=a;
System.out.println(a==b);
a="Chawla";
System.out.println(a +b);
Output:
true
ChawlaParas
·
Synchronization and concurrency: making String immutable automatically makes them
thread safe thereby solving the synchronization issues. Since String is immutable it can safely share between many
threads which is very important for multithreaded programming and to avoid any
synchronization issues in Java, Immutability also makes String instance
thread-safe in Java, means you don't need to synchronize String operation
externally.
·
Caching: when compiler optimizes your String objects, it sees that if
two objects have same value (a="test", and b="test") and
thus you need only one string object (for both a and b, these two will point to
the same object). String is immutable, no one can change its
contents once created which guarantees hashCode of String to be same on
multiple invocations.
·
Class loading: String is used as arguments for class
loading. If mutable, it could result in wrong class being loaded (because
mutable objects change their state). Had String
been mutable, a request to load "java.io.Writer" could have been changed to load "mil.vogoon.DiskErasingWriter"
If I have class with all static members is it immutable?
If your class has only static
members, then objects of this class are immutable, because you cannot change
the state of that object ( you probably cannot create it either :) )
No comments:
Post a Comment