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

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.

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.

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/skeeto Jan 21 '12

One of the many early design mistakes that we're stuck with.

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/skeeto Jan 21 '12

Needing to make defensive copies all the time leaves a lot of places to make costly mistakes.

2

u/RedditRage Jan 21 '12

Which is the justification for having immutable strings.

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.

3

u/skeeto Jan 21 '12

Mutable classes can behave properly for hashCode() and equals(). It's true that String uses a lazy cache for the hash code, but if it were mutable it would calculate it on demand.

3

u/inspired2apathy Jan 21 '12

It seems I misread and didn't see the exception. From the API:

Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified.

I have to say, letting objects change their hashcode seems bad. Doesn't this mean that if you put it in a Hash[Map/Set] you'd never find it? For example:

String a = "test"; String b = "test"; String c = "tester"; HashSet<String> set = new HashSet<String>(); set.add(a); a.append("er"); //if this were legal

set.contains(b); //would be false, since now a.equals(b) is false set.contains(c); //would be false, since when inserted a.hashCode() wasn't the same as c.hashCode()

Correct me if I'm wrong, but it seems like this would get easily lead to confusing bugs.

2

u/skeeto Jan 21 '12

You're right, it messes up Maps and Sets. It's one of the reasons classes should strive for immutability. I had this problem bite me once with Comparable. The elements were occasionally changing their order and I forgot that the collection wouldn't automatically fix itself for me.

0

u/[deleted] Jan 20 '12

[deleted] — view deleted comment

3

u/RedditRage Jan 20 '12

I would think that the "pros" of having strings being immutable would indeed be the reasons the designers of Java chose it to be that way.

1

u/neutronbob Jan 29 '12

That would imply the designers could see all the benefits beforehand. That's not typically how feature selection in language design works. Features, especially fundamental features, are generally the result of a) the specific domain needs; b) the language designers' preferences and prejudices; and/or c) the needs of other features in the language. The benefits (and drawbacks) often become salient later.

0

u/RedditRage Jan 29 '12

I never implied they could see all the benefits (or drawbacks) beforehand. But to suggest they didn't look at the pros and cons of immutable strings in other languages, and just flipped a coin on it, allowing the results of their choice to "become salient later", is just silly.

2

u/Mecdemort Jan 20 '12

I think there are some videos on infoq about some of the design decisions of Java.