Java StringBuilder reverse() Method



The Java StringBuilder reverse() method is used to reverse the characters of a StringBuilder 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 StringBuilder reverse() method −

public StringBuilder reverse()

Parameters

  • It does not accept any parameter.

Return Value

This method returns a reference to this object.

Example

If the StringBuilder 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 StringBuilder class with the value “TutorialsPoint”. Using the reverse() method, we are trying to reverse its characters.

package com.tutorialspoint.StringBuilder;
public class Reverse {
   public static void main(String[] args) {
      
      //instantiating the StringBuilder class
      StringBuilder sb = new StringBuilder("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 StringBuilder 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.

package com.tutorialspoint.StringBuilder;
public class Reverse {
   public static void main(String[] args) {
      
      //instantiating the StringBuilder class
      StringBuilder sb = new StringBuilder("malayalam");
      System.out.println("The given string: " + sb);
      
      //using the reverse() method
      StringBuilder 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_stringbuilder.htm
Advertisements