9/15/2006

Reverse a String with StringBuilder or StringBuffer

Both StringBuilder and StringBuffer class have a reverse method. They work pretty much the same, except that methods in StringBuilder are not synchronized. This is the signature of StringBuilder.reverse:

public StringBuilder reverse()
This method returns an instance of StringBuilder. The interesting thing is, the returned value is actually itself. So what this method does is, it reverses itself and returns itself. This is the source code for StringBuilder.reverse:
public StringBuilder reverse() {
super.reverse();
return this;
}
In the following example, the old and the reversed string will print the same content after calling reverse method:
public static void main(String[] args) {
StringBuilder old = new StringBuilder(args[0]);
StringBuilder newsb = old.reverse();
System.out.println("original string: " + old);
System.out.println("new string: " + newsb);
}
If you still need to access the original content of the StringBuilder, you will need to save it to string before invoking sb.reverse().