Java StringBuffer reverse() Method



The Java StringBuffer reverse() method is used to reverse the characters of a StringBuffer object. It replaces the sequence of characters in reverse order. The method is a static method with predefined logic for reversing a string in Java.

The reverse() method does not accept any parameters, and it does not throw any exception while reversing the character's sequence.

Syntax

Following is the syntax of the Java StringBuffer reverse() method −

public StringBuffer reverse()

Parameters

  • It does not accept any parameter.

Return Value

This method returns a reference to this object.

Example

If the StringBuffer class object does not contain the null value, the reverse() method reverses its contents and returns the resultant object.

In the following program, we are instantiating the StringBuffer class with the value “TutorialsPoint”. Using the reverse() method, we are trying to reverse its characters.

public class Reverse {
   public static void main(String[] args) {
      //instantiating the StringBuffer class
      StringBuffer sb = new StringBuffer("TutorialsPoint");
      System.out.println("The original string before reverse: " + sb);
      //using the reverse() method
      System.out.println("After reverse the string: " + sb.reverse());
   }
}

Output

On executing the above program, it will produce the following result −

The original string before reverse: TutorialsPoint
After reverse the string: tnioPslairotuT

Example

Using the reverse() method, we can reverse a string and this reversed string can be used to check whether it is a palindrome string or not.

In the following example, we are creating an object of the StringBuffer class with the value "malayalam". Then, using the reverse() method we reverse the string. Using the equals() method, we are trying to check whether the string is equal to the reverse string or palindrome string or not.

public class Reverse {
   public static void main(String[] args) {
      //instantiating the StringBuffer class
      StringBuffer sb = new StringBuffer("malayalam");
      System.out.println("The given string: " + sb);
      //using the reverse() method
      StringBuffer reverse_str = sb.reverse();
      System.out.println("The reverse the string: " + reverse_str);
      if(("malayalam".equals(String.valueOf(reverse_str)))) {
         System.out.println("The sting is palindrome string");
      } else {
         System.out.println("The string is not a palindrome string");
      }
   }
} 

Output

Following is the output of the above program −

The given string: malayalam
The reverse the string: malayalam
The reverse string is equal to original string
java_lang_stringbuffer.htm
Advertisements