[offtopic] RE: [jdom-interest] Text class

Alex Rosen arosen at silverstream.com
Thu May 31 14:43:28 PDT 2001


[Just getting back from vacation...]

> Forgive me if this is terribly naive, but does any one know why
> java.lang.String* are final?  

As someone else mentioned, String is final so it can be guaranteed to be
immutable for security reasons. (So you can't give someone a String, such as to
an IP address, and then modify it later on, after they've checked it for
security.)

StringBuffer is final for the same reason, and here's why. String and
StringBuffer work together to implement copy-on-write. String and StringBuffer
both internally use char arrays to store their data. When you call
StringBuffer.toString(), it gives you a String that points to its internal char
array, rather than making a copy. This saves time and memory, in the common
case where you don't modify the StringBuffer after calling toString() on it.
Then, in every modification method, StringBuffer checks to see if there's a
String that's sharing its array, and if so, it copies the array first, so that
the String isn't affected by the change. If StringBuffer weren't final, someone
could undermine the security system by changing this behavior.

This feature is what makes it OK for the Text class to use StringBuffer, in my
mind. Every call to Text.toString() will result in a new String object being
created, which is somewhat unfortunate, but at least the char array won't have
to be copied each time (in the common case where all the modification happens
up front, before any accessors are called). 

Alex Rosen
SilverStream Software
-------------- next part --------------
A non-text attachment was scrubbed...
Name: winmail.dat
Type: application/ms-tnef
Size: 2348 bytes
Desc: not available
Url : http://jdom.org/pipermail/jdom-interest/attachments/20010531/f83612c4/winmail.bin


More information about the jdom-interest mailing list