Reverse a String In Java Using Recursion

Reverse a String In Java Using Recursion | Recursion is a technique to divide the problem into smaller components so that we can solve the problem easily. Previously we have seen different approaches to reverse a string in Java programming. Now, we will see how to reverse a string in Java using recursion.

Program to Reverse a String In Java Using Recursion

public class Main {
   public static void reverseString(String string) {
      if ((string == null) || (string.length() <= 1))
         System.out.println(string);
      else {
         System.out.print(string.charAt(string.length() - 1));
         reverseString(string.substring(0, string.length() - 1));
      }
   }

   public static void main(String[] args) {
      String string = "Hello World!";
      System.out.println("String: " + string);
      System.out.print("String after reverse: ");
      reverseString(string);
   }
}

Output:-

String: Hello World!
String after reverse: !dlroW olleH

We have defined a reverseString() method which uses the recursion technique to display the reverse of a string in Java. In this method, first, we find out the length of the given string. If the string length is 0 or less than 0 then we just print the string, else we will reverse the string and print it on the output screen. 

For recursive calls internally it is using the substring() method and removes the last character from the input string. In the main function, we take a string and call reverseString() method recursively to reverse the string.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *