Why is it that they decided to make String
immutable in Java and .NET (and some other languages)? Why didn\'t they make it mutable?
Wow! I Can't believe the misinformation here. String
s being immutable have nothing with security. If someone already has access to the objects in a running application (which would have to be assumed if you are trying to guard against someone 'hacking' a String
in your app), they would certainly be a plenty of other opportunities available for hacking.
It's a quite novel idea that the immutability of String
is addressing threading issues. Hmmm ... I have an object that is being changed by two different threads. How do I resolve this? synchronize access to the object? Naawww ... let's not let anyone change the object at all -- that'll fix all of our messy concurrency issues! In fact, let's make all objects immutable, and then we can removed the synchonized contruct from the Java language.
The real reason (pointed out by others above) is memory optimization. It is quite common in any application for the same string literal to be used repeatedly. It is so common, in fact, that decades ago, many compilers made the optimization of storing only a single instance of a String
literal. The drawback of this optimization is that runtime code that modifies a String
literal introduces a problem because it is modifying the instance for all other code that shares it. For example, it would be not good for a function somewhere in an application to change the String
literal "dog"
to "cat"
. A printf("dog")
would result in "cat"
being written to stdout. For that reason, there needed to be a way of guarding against code that attempts to change String
literals (i. e., make them immutable). Some compilers (with support from the OS) would accomplish this by placing String
literal into a special readonly memory segment that would cause a memory fault if a write attempt was made.
In Java this is known as interning. The Java compiler here is just following an standard memory optimization done by compilers for decades. And to address the same issue of these String
literals being modified at runtime, Java simply makes the String
class immutable (i. e, gives you no setters that would allow you to change the String
content). String
s would not have to be immutable if interning of String
literals did not occur.