| Author |
Why are Strings Immutable ?
|
Arvind Sampath
Ranch Hand
Joined: May 11, 2005
Posts: 144
|
|
Strings in Java are Immutable. But then ,why is it so ? I have gone through quite a few resources in the Net which deal with Immutability of Strings. But still am not able to get into a conclusion as to why Strings were made immutable at first. I have a fairly good understanding of the String Literal Pool concept. I guess am missing something. Pls help me on this. Thanks in Advance. Regards, Arvind
|
 |
Mani Ram
Ranch Hand
Joined: Mar 11, 2002
Posts: 1140
|
|
Performance, Safety, Simplicity. Think about it for sometime. See whether you can appreciate the idea of having the String class as immutable based on the above mentioned points.
|
Mani
Quaerendo Invenietis
|
 |
Arvind Sampath
Ranch Hand
Joined: May 11, 2005
Posts: 144
|
|
Thanks Mani! Can u pls elaborate a little? Am still not clear. Regards, Arvind
|
 |
Kai Witte
Ranch Hand
Joined: Jul 17, 2004
Posts: 354
|
|
hello, I recommend "Effective Java" (Bloch), "Chapter 13: Favor immutability" about this topic. Beside the advantages Mani listed immutable data objects are thread-safe, can be shared freely(*), and they are great "building blocks" for other objects. The apparent disadvantages (a separate object is required for each distinct value, thus they are not good for multistep operations) can easily be negated by providing a mutable companion type, like StringBuilder and StringBuffer for String. However, this is implemented poorly in the core api. The best general approach for providing an immutable and a mutable type is to have one interface for the immutable type, and one interface that extends this interface for the mutable type.
I have gone through quite a few resources in the Net which deal with Immutability of Strings.
Big mistake. Just get "Effective Java" (Bloch). Kai (*) Consider an In the implementation getName can simply return a private String name without making a copy of it. The client of the api can not modify the internals of Customer by modifying the String, because it is immutable.
|
Kai Witte's business website Kai Witte's private homepage Mock exam / preparation kit reviews
|
 |
Arvind Sampath
Ranch Hand
Joined: May 11, 2005
Posts: 144
|
|
Thanks Kai!
In the implementation getName can simply return a private String name without making a copy of it. The client of the api can not modify the internals of Customer by modifying the String, because it is immutable.
I have been using these getter methods all along, but never thought on these lines.I can now appreciate the reasons for making Strings immutable. Regards, Arvind
|
 |
 |
|
|
subject: Why are Strings Immutable ?
|
|
|