Reverse a string using recursion in Java

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:

1streverseString(star)
2ndreverseString(tar)s
3rdreverseString(ar)ts
4threverseString(r)ats
5thrats

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
 

Post a comment

Name

Your Comment

Email (We dont publish it)

Comments

Nothing yet..be the first to share wisdom.