How can I reverse a string in Java?

Java 8Object Oriented ProgrammingProgramming

The StringBuffer class has a method named reverse() which will reverse the contents of the current buffer. The program buffers the input String using StringBuffer (String string) method, reverse the buffer and then converts the buffer into a String with the help of toString() method.

Example

 Live Demo

public class Sample {
   public static void main(String args[]){
      String str = new String("Hello how are you");
      StringBuffer sb = new StringBuffer(str);
      String str2 = sb.reverse().toString();
      System.out.println(str2);
   }
}

Output

uoy era woh olleH
raja
Published on 05-Jul-2019 10:47:22
Advertisements