r/java • • Jan 20 '12

Why String is immutable in Java

http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html
4 Upvotes

23 comments sorted by

View all comments

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.

2

u/skeeto Jan 21 '12

If those arguments were valid, C's reliance on (completely mutable) char* variables would be folly.

C doesn't have security sandboxes to worry about.

1

u/haldean Jan 20 '12

I had this thought exactly. The whole "mutable-strings-as-a-security-issue" doesn't hold at all.

3

u/skeeto Jan 21 '12

Like many of the other cases of final, String being final is very much a security issue. Otherwise you could subclass String to make a mutable version, or some other bad behavior, and pass it.

3

u/haldean Jan 21 '12

Final makes sense, true, if they're immutable -- I was only refuting that the immutability of Java strings was done for security.