-2

Possible Duplicate:
Why can't strings be mutable in Java and .NET?
What's the advantage of a String be Immutable?

can any one please tell me why String class has been created as immutable class, Any valid reason behind this Design approach?

Please share your thoughts

1
  • A very common question which would have been answered by google. Commented Jan 11, 2012 at 17:39

2 Answers 2

2

Because if the String class was not final then you could declare a subclass of String which breaks any number of the contracts of the String class, especially immutability, and wreak havoc on unsuspecting programmers.

Imagine:

class MyString extends String {
  // Override methods which mutate this instance...
}

Now whenever a MyString is passed around as a String it could cause all sorts of problems, especially regarding hashing, which depends on the immutability of String.

Sign up to request clarification or add additional context in comments.

Comments

0

Because it makes them much easier to use:

  • thread safe without synchronization
  • usable as a key in Maps
  • no need to create defensive copies each time you pass or return them
  • poolable
  • ...

2 Comments

These are all great reasons and (correct me if I'm wrong) they all effects of the immutability of string contents, no?
The question is: "why is the String class immutable?". It's not "why is the String class final?".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.