String is immutable.Everywhere we read about how spring is immutable.But what I want to know is Why is string immutable. Why have to made string immutable.Had problem would have they faced had string not been immutable.
Search these forums. This question has been asked many times.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Joined: Jul 07, 2012
Thanks. I had already searched for this. Everyone has written how string is immutable. Everyone knowing some core java know the string is immutable and everywhere on google they tell how it is immutable but now one talks on why it has been made so.
I did a quick search on this forum and found dozens of topics for 'Why is String immutable".
The short answer is that nobody here knows the exact reasons why the designers of the language made the choices they did. We can make some guesses, but in the end, that's the best anyone here can do. So, search here, read what folks say, and I'm sure you'll have a better understanding.
Have you had a look at any of the posts that Fred suggested?
However, just a few advantages off the top of my head:
1. It makes Strings Thread-safe.
2. It means that they are safe for use as keys in Maps.
3. It means that their hashcode can be cached as and when needed.
4. It means that their internals can be shared between instances. substring(), for example, does NOT copy the internal character array, it simply creates a new String with a different start offset and length.
Also, there is already a mutable "String" class (in fact, two of them) - StringBuilder. So why would you not want String to be immutable?
My advice: If you're writing a class of your own, make it immutable unless you have a very good reason not to. It just makes life easier.
Isn't it funny how there's always time and money enough to do it WRONG?
Artlicles by Winston can be found here
Ivan Jozsef Balazs
Joined: May 22, 2012
Winston's points shed light on the reasons for the immutability but also for String's being final. Otherwise you could derive from String and undermine it.
Note that the Java designers were very very aware of deficiencies in C which led to many bugs and exploits. Buffer over-runs etc. Immutable Strings prevent certain bugs / exploits that were common in C programs.
But it is not String's being immutable which prevents buffer overrun and dangling pointers etc. errors in Java.
You can not make a (n unchecked) buffer overrun error in Java with an array or with a StringBuilder or with a StringBuffer either.