Reverse of a String using recursion in Java

Reverse of a String with out using Library functions is a general interview question.For any such questions, check whether the problem can be solved with Algorithmic Design techniques. Most of the problems that contain loops can be re-written as recursive programs, can be a solution for such interview questions. Recursion and Divide and Conquer strategy of Algorithmic Design Techniques can be used to solve problems of such kind.

Algorithm for Reverse of a String using Recursion

Base Case: if String length is less than 2, i.e., if string is devised to one character then return the character.
Recursive: Extract first character, call method to itself on the sub problem i.e., with sub string leaving first character. Append every first character of the sub problem to the end of the result.

Here is the implementation for Reverse of a string using recursion in java

package com.jminded.recursion;

public class ReverseOfStringUsingRecursion {

	/**
	 * @author Umashankar
	 * {@link https://jminded.com}
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		String s="This is Recursion Tutorial";
		System.out.println(reverseString(s));
 	}
	/**
	 * <p> Reverse of a String using Recursion</p>
	 * @param str
	 * @return
	 */
	public static String reverseString(String str) {

        //base case to handle one char string and empty string
        if (str.length() < 2) {
            return str;
        }else{  //recursive case
        return reverseString(str.substring(1)) + str.charAt(0);
        }

    }

}

Leave a Comment