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.
public class StringBufferMethodDemo
public static void main(String args)
StringBuffer sb1 = new StringBuffer("ABCDEF");
System.out.println("Original StingBuffer object sb1: " + sb1);
StringBuffer sb2 = sb1.reverse();
System.out.println("StingBuffer object sb1 after reversing: " + sb1);
System.out.println("Returned StingBuffer object sb2: " + sb2);
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