This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Sebastian Janisch wrote:This means that for instance Hello becomes
and you end up with 4 new String objects on the heap.
Not necessarily. The string exists out of characters, so you can get those into a new char, then do swaps inside that char. In code:
This requires a char besides the new String, so if the String contains 1.000.000 characters that means 3.000.000 characters in memory (original String, temporary char, reversed String). However, if String would have a reverse method then it could skip the temporary char; String has a package private method (since at least Java 1.4) that can be used for this:
(the other String constructors that take a char make a copy of that char)
This means that if String would have a reverse method, it could actually make the temporary char part of the reversed String, therefore requiring only 2.000.000 characters in memory. The same code as it would be when part of String:
However, this method does not exist, so using an intermediate StringBuffer or StringBuilder, or code like at the top of my post, is all that remains.
The idea (as Sebastian Janisch) has already said is that String is for immutability and StringBuilder (usually better than StringBuffer) is for changing text. So many changing methods are moved into StringB...er.