i am trying to do a simple string manipulation. input is “murder”, i want to get “murderredrum”.
i tried this
String str = "murder";
StringBuffer buf = new StringBuffer(str);
// buf is now "murder", so i append the reverse which is "redrum"
buf.append(buf.reverse());
System.out.println(buf);
but now i get “redrumredrum” instead of “murderredrum”.
can someone explain what’s wrong with my program? thank you.
The short answer
The line:
essentially does the following:
This is why you get
"redrumredrum".That is,
buf.reverse()doesn’t return a newStringBufferwhich is the reverse ofbuf. It returnsbuf, after it had reversed itself!There are many ways to "fix" this, but the easiest would be to explicitly create a new
StringBufferfor the reversal, so something like this:Deeper insight: comparing
StringandStringBufferStringin Java is immutable. On the other hand,StringBufferis mutable (which is why you can, among other things,appendthings to it).This is why with
String, a transforming method really returns a newString. This is why something like this is "wrong"Instead you want to do:
However, the situation is far from analogous with
StringBuffer. MostStringBuffermethods do returnStringBuffer, but they return the same instance that it was invoked on! They do NOT return a newStringBufferinstance. In fact, you’re free to discard the "result", because these methods have already accomplished what they do through various mutations (i.e. side effects) to the instance it’s invoked upon.These methods could’ve been declared as
void, but the reason why they essentiallyreturn this;instead is because it facilitates method chaining, allowing you to write something like:Related questions
Appendix:
StringBuffervsStringBuilderInstead of
StringBuffer, you should generally preferStringBuilder, which is faster because it’s notsynchronized. Most of the discussions above also applies toStringBuilder.From the documentation:
Related questions
Bonus material! Alternative solution!
Here’s an alternative "fix" to the problem that is perhaps more readable:
Note that while this should do fine for short strings, it does use an extra buffer which means that it’s not the most efficient way to solve the problem.
Related questions
CharSequence, yes this can be done!Bonus material again! The last laugh!