Can we have a discussion about it? ;)
Why String is immutable?
Collapse
X
-
Note that this 'space saving' trick can turn its head against you; have a look at the following code snippet:
The substring() method shares its char[] buffer with the String for which it is a substring and the entire String buffer can not be garbage collected. Line two from the above code snippet had better written as:Code:String humongous= ... ; // an extremely big String String small= humongous.substring(0, 1): // a very small String humongous= null; // free the big one?
The String constructor guarantees that a new char[] buffer will be used.Code:String small= new String(humongous.substring(0, 1));
kind regards,
JosComment
-
Comment
-
I hope below comments make every one in commendable position to answer " Why String is immutable".
Look at this example: We have a file open method with login check. We pass a String to this method to process authentication which is necessary before the call will be passed to OS. If String was mutable it was possible somehow to modify its content after the authentication check before OS gets request from program then it is possible to request any file. So if you have a right to open text file in user directory but then on the fly when somehow you manage to change the file name you can request to open "passwd" file or any other. Then a file can be modified and it will be possible to login directly to OS.
Note: I do agree with "String pool implementation and the performance gains of the String pool" but it all w.r.t VM rather than OS.
Cheers
BuntyComment
-
Note that this 'space saving' trick can turn its head against you; have a look at the following code snippet:
The substring() method shares its char[] buffer with the String for which it is a substring and the entire String buffer can not be garbage collected. Line two from the above code snippet had better written as:Code:String humongous= ... ; // an extremely big String String small= humongous.substring(0, 1): // a very small String humongous= null; // free the big one?
The String constructor guarantees that a new char[] buffer will be used.Code:String small= new String(humongous.substring(0, 1));
kind regards,
Jos
The substring() method shares its char[] buffer with the String for which it is a substring and the entire String buffer can not be garbage collected. Line two from the above code snippet had better written as:Code:String humongous= ... ; // an extremely big String String small= humongous.substring(0, 1): // a very small String humongous= null; // free the big one?
This is not right. Call to substring is going to call the constructor String(original String, startIndex, offset). So the substring is not sharing the char[] from original stringCode:String small= new String(humongous.substring(0, 1));
Comment
Comment