How to reverse a given string in Java?



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
Rishi Raj
Rishi Raj

I am a coder


Advertisements