-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

Community
  • 1
  • 1
gmhk
  • 15,093
  • 27
  • 86
  • 109

2 Answers2

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.

maerics
  • 143,080
  • 41
  • 260
  • 285
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
  • ...
JB Nizet
  • 657,433
  • 87
  • 1,179
  • 1,226
  • These are all great reasons and (correct me if I'm wrong) they all effects of the immutability of string contents, no? – maerics Jan 11 '12 at 17:32
  • The question is: "why is the String class immutable?". It's not "why is the String class final?". – JB Nizet Jan 11 '12 at 17:39