In: Computer Science
In Java, write a recursive function that accepts a string as its argument and prints the string in reverse order. Demonstrate the function in a driver program.
Answer)
Java program for the recursive function that accepts a string as
its argument and prints the string in reverse order:
public class StringReversalRecursion {
public static void main(String[] args) { // Driver
main
String input = "This is a
Test";
//Next stage, we pass the input
string to the method
String output =
reverseMethod(input); // Receiving the output from the recursive
method
System.out.println("The output
string is: " + output);
}
//Following method is used for reversal of the stirng
and checking if the input stirng is empty or not. Recursion occurs
in this method
public static String reverseMethod(String input)
{
if (input.isEmpty()){ // checking
if the input is empty or not
System.out.println("String Reversal
is complete.");
return input;
}
//Recursion calls
return
reverseMethod(input.substring(1)) + input.charAt(0); // recursive
calls for the method
}
}
Output:
String Reversal is complete.
The output string is: tseT a si sihT
Here we are using the string "This is a Test" as input and
getting the output:
tseT a si sihT
using recursive method as defined : reverseMethod
**Please Hit Like if you appreciate my answer. For further doubts on the answer please drop a comment, I'll be happy to help. Thanks for posting.**