Reverse the sequence of characters in a StringBuffer Object in Java

Java 8Object Oriented ProgrammingProgramming

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();
raja
Published on 03-Jan-2019 16:30:17
Advertisements