Reverse a String Using Recursion in Java



In this article, we will learn to reverse a string using recursion in Java. Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function. You can reverse a string using the recursive function as shown in the following program.

Steps to reverse a string using recursion 

Following are the steps to reverse a string using recursion ?

  • Create a class called StringReverse with a method reverseString that takes a string as input.
  • In the reverseString method, use an if else statement to check if the string is empty. If it is, return the string as-is to stop the recursion.
  • If the string is not empty, use else to call reverseString recursively on the substring starting from the second character str.substring().
  • After each recursive call, concatenate the first character str.charAt() to the result returned by the recursive function.
  • In the main method, initialize an object of StringReverse and call reverseString with a sample string.
  • Print the result to display the reversed string on the console.

Java program to reverse a string using recursion

Below is the Java program to reverse a string using recursion ?

public class StringReverse {
   public String reverseString(String str){
   
      if(str.isEmpty()){
         return str;
      } else {
         return reverseString(str.substring(1))+str.charAt(0);
      }
   }
   public static void main(String[] args) {
      StringReverse obj = new StringReverse();
      String result = obj.reverseString("Tutorialspoint");
      System.out.println(result);
   }
}

Output

tniopslairotuT

Code explanation

In this article, the StringReverse class, the reverseString method checks if the string is empty. If not, it calls itself with the substring starting from the second character. This recursive process continues until an empty string is reached, forming the base case. When returning, each first character from the calls is added back in reverse order, effectively reversing the entire string. Finally, in the main method, we create an object and call it reverseString with "Tutorialspoint" to see the reverse result.

Updated on: 2024-11-08T22:29:10+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements