I qoute from Herbert Schildt book on Java, Chapter String Handling,
The
append( )
method is most often called when the+
operator is used on String objects. Java automatically changes modifications to a String instance into similar operations on a StringBuffer instance. Thus, a concatenation invokesappend( )
on a StringBuffer object.
I know very well that a concatenation invokes append( )
on a StringBuffer instance. What does the author mean by saying "append( )
method is most often called when the +
operator is used on String objects"? As per my understanding 'append()' cannot be used with strings.
After the concatenation has been performed, the compiler inserts a call to
toString( )
to turn the modifiable StringBuffer back into a constant String. All of this may seem unreasonably complicated. Why not just have one string class and have it behave more or less like StringBuffer? The answer is performance. There are many optimizations that the Java run time can make knowing that String objects are immutable. Thankfully, Java hides most of the complexity of conversion between Strings and StringBuffers. Actually, many programmers will never feel the need to use StringBuffer directly and will be able to express most operations in terms of the + operator on String variables.
I wish to know what are the optimizations that the Java run time can make knowing that String objects are immutable?
Elaborating with a code always yields for me a better understanding for the mentioned problem?
I wish to know what are the optimizations that the Java run time can make knowing that String objects are immutable?
For starters, there's the string pool -- any string literals in your program will be interned; different classes that both refer to string literals with the same contents will just refer to the same object in memory.
In crazier news, there's an option in recent versions of the Java garbage collector where, under certain conditions, the garbage collector will detect multiple String
objects with the same contents and edit them to point to the same backing char[]
. This is only possible because Strings are immutable, and allows the garbage collector to silently (and semantics-preservingly) reduce memory consumption.