Reverse the sequence of characters in a StringBuffer Object in Java


In order to reverse the sequence of characters in a StringBuffer Object, we use the reverse() method. The reverse() method replaces the character sequence with the reverse of its own.

Declaration − The java.lang.StringBuffer.reverse method is declared as follows−

public StringBuffer reverse()

Let us see a program to reverse the sequence of characters in a StringBuffer Object using the reverse() method.

Example

 Live Demo

public class Example {
   public static void main(String[] args) {
      StringBuffer sb = new StringBuffer("Hello World");
      System.out.println("Original StringBuffer Object: " + sb);
      sb.reverse();
      System.out.println("New StringBuffer Object: " +sb);
   }
}

Output

Original StringBuffer Object: Hello World
New StringBuffer Object: dlroW olleH

Let us understand the above program. We created a StringBuffer Object

StringBuffer sb = new StringBuffer("Hello World");

After that we used the reverse() method to reverse the StringBuffer Object

sb.reverse();

Updated on: 26-Jun-2020

147 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements