How to reverse a given string in Java?

Java 8Object Oriented ProgrammingProgramming

StringBuffer class provides you a method named reverse() to reverse its contents. One way to reverse a String is to append it to the StringBuffer object reverse it and convert it back to String.

Example

Live Demo

public class ReverseString {
   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 10-Jan-2018 10:38:22
Advertisements