Here is a Java program to reverse a string using recursion method. This is one of the frequently asked question for Java and C programming interviews to measure a candidate's knowledge of recursion technique. However in practise you might use iterative method ( for loop) to reverse a string rather than recursion.
This program use the Scanner
class to read a string from the standard input (console). Next, the reverseString(String str)
recursive function is invoked with input string as parameter. This function recursively calls itself until the length of the parameter string equals 1. Each function call removes and returns the first character of the argument string.
The reverseString() function can be better explained with an example. Let's say the input string is star. Then each function call and their return values will be as below:
1st | reverseString(star) | |||
2nd | reverseString(tar) | s | ||
3rd | reverseString(ar) | t | s | |
4th | reverseString(r) | a | t | s |
5th | r | a | t | s |
Program
import java.util.Scanner; public class StringReverse { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); String inputStr; System.out.println("Enter the string to reverse"); inputStr = keyboard.nextLine(); System.out.println(reverseString(inputStr)); } public static String reverseString(String str){ if (str.length() == 1) { return str; } return reverseString(str.substring(1)) + str.charAt(0); } }
Output
Output from the above program will be like this
Enter the string to reverse star rats