reverse() StringBuffer Example

reverse() StringBuffer Example

StringBuffer comes with many utility methods to do operations on strings apart String class own methods. One such method is reverse() method.

StringBuffer, with its nature of mutability, comes with many methods that do not exist in String. One useful method is reverse() method which reverses the existing contents in the StringBuffer. Anywhere in Java, if reversing is required, this is the only method available (except Collections.reverse() where data structure elements are reversed).

Following is the method signature as defined StringBuffer class.

  • public StringBuffer reverse(): The characters prsent in the StringBuffer are reversed (first becomes last and last becomes first).

In the following example, the string "ABCDEF" is reversed.


1. The reverse() method reverses the contents in the original StringBuffer (here, sb1) itself.
2. The reverse() method return value is StringBuffer. The returned StringBuffer object (here, sb2) also contains reversed contents. See the screenshot.

You have seen how to reverse the contents of StringBuffer. Then, how to reverse the contents of a string. reverse() method does not exist in String class. It is required to convert string into StringBuffer. An example program with screenshot is shown at String reverse with and without reverse() Example

Leave a Reply

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