Java Program to find out the reverse of a string using recursion.


February 14, 2022, Learn eTutorial
1176

Here we are explaining how to write a java program to find out the reverse of a string. So first we have to read the string from the user. Then call the recursive function reverse() to find out the reverse of the string.

How to implement the java program to find out the reverse of a string using recursion?

First, we have to declare the class ReverseStr .Then declare the string variable str. Then read the string from the user into the variable str. Then we call the recursive function reverse(str) to find out the reverse of the string. Then we will display the reversed string.

In the function reverse(string str),check if the string is empty or not by using the function isEmpty().If true then return str.Else return  reverse(str.substring(1)) + str.charAt(0).

ALGORITHM

STEP 1: Declare the class ReverseStr with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3: Declare the string variable str.

STEP 4: Read the string from the user.

STEP 5: Call the function reverse(str) to find out the reverse of the string.

STEP 6: Display the reversed string as rstr.

FUNCTION reverse(String str)

STEP 1:Check if str is empty or not, if empty then return str.

STEP 2: Else return reverse(str.substring(1)) + str.charAt(0)

 

Java Source Code

                                          import java.util.Scanner;
public class ReverseStr {

 public static void main(String[] args) {
  String str;
  System.out.println("Enter the string: ");
  Scanner sc = new Scanner(System. in );
  str = sc.nextLine();
  sc.close();
  String rstr = reverse(str);
  System.out.println("The reversed string is: " + rstr);
 }

 public static String reverse(String str) {
  if (str.isEmpty()) return str;

  return reverse(str.substring(1)) + str.charAt(0);
 }
}
                                      

OUTPUT

Enter the string: stem
The reversed string is: mets