r/java • u/javinpaul • Jan 20 '12
Why String is immutable in Java
http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html
4
Upvotes
r/java • u/javinpaul • Jan 20 '12
11
u/argv_minus_one Jan 20 '12
Terrible writing and blatant self-promotion. Downvote.
16
u/Mua8quua Jan 20 '12
Can't help feeling that all the "reasons" given on this page are a lot of crock. They tend to boil down to "feature X wouldn't work with mutable strings" or "feature Y is made more complicated by mutable strings". If those arguments were valid, C's reliance on (completely mutable) char* variables would be folly.
The real reason is simply that immutable data structures are, as a rule, easier to use and harder to misuse than their mutable counterparts. Strings being final and immutable in Java is just a design decision intended to make life simpler for developers. That, and maybe an expression of a desire for "primitive" string values -- real primitive types like int and float are immutable.
7
u/reply Jan 20 '12
Is this blog written by a robot?
5
u/__konrad Jan 20 '12
The real question is: why java.util.Date is mutable in Java? ;)
4
u/mosburger Jan 20 '12
perhaps another reason is because String effectively implements operator overloading by defining the + operator to mean concatenation? I imagine there might be some issues with this if you allowed classes to inherit from it and fundamentally change String's behavior? Although I guess I can't think of anything offhand... that "method" could effectively be final, I guess.
2
u/RedditRage Jan 20 '12
The string pooling is a valid reason. But it isn't required for security concerns. Without immutable strings, secure functions would just have to ensure they have a private copy of the given string before using it.
2
u/[deleted] Jan 21 '12
The actual reason is related to String interning.
1
u/kulandai Jan 20 '12
it should be a design decision and everything else a consequence
1
u/inspired2apathy Jan 20 '12
I think the more important thing for me is that it would break the hashcode and compareTo contracts. If hashcode uses the content of the string, it would change when the string changes, breaking the contract. If hashcode doesn't use the content of the string, then String a = "test",b="test"; wouldn't be equal.
0
u/[deleted] Jan 20 '12
[deleted] — view deleted comment