How can I reverse a string in Java?



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

Advertisements