Hackerss.com

hackerss
hackerss

Posted on

Reverse a string in Java

Reverse a string - Java:


public class ReverseString {
   /**
   * This method reverse a string.
   * @param str String to reverse.
   * @return String Obtains the reverse of str.
   */   
   public String reverseString(String str) {
       //Variable to store the reverse string
       String reverse = "";
       //Reverse the string
       for (int i = str.length() - 1; i >= 0; i--) {
           reverse += str.charAt(i);
       }
       //Return the reverse string
       return reverse;
   }

   /**
   * One Example
   */
   public static void main(String args[]) throws IOException {

      ReverseString  reverseString= new ReverseString ();
      //Example
      String str = "Hello World";
      String reverse = reverseString.reverseString(str);
      //Output
      System.out.println("Reverse of " + str + " is :" + reverse); //dlroW olleH
   }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)