reverse() StringBuffer Example

reverse() StringBuffer Example


java.lang.StringBuffer class comes with many utility methods to manipulate string. One of the method is reverse() used to reverse the contents of the buffer. After this method call, original buffer itself gets effected.

Note: reverse() is not a method of String; applying on string raises compilation error.

What Java API says about reverse() StringBuffer:
  • public synchronized StringBuffer reverse(): Reverses the contents of the buffer. Returns a StringBuffer object. The returned object and the original buffer object, both contain the reversed string only. See example.

Following example illustrates the usage of reverse() StringBuffer method in all possible ways.


reverse() StringBuffer
Output screenshot of reverse() StringBuffer

Another example on reverse() method. It is to reverse a string and check for a Palindrome.


reverse() StringBuffer
Output screenshot of Palindrome of reverse() StringBuffer

StringBuffer sb1 = new StringBuffer(str1);
sb1.reverse();

Reverse is not a method of String class but of StringBuffer. For this reason, String str1 is converted into a StringBuffer object sb1 and then reversed.

String str2 = sb1.toString();

Again after reversing, the StringBuffer object sb1 is converted to String, with toString() method, to compare with the original String object str1. The whole can be converted into simple code using anonymous objects as follows.

Leave a Reply

Your email address will not be published. Required fields are marked *