Java program to reverse a string using recursion

Program

import java.util.Scanner;
class ReverseStringRecursion {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a string:");
        String str = sc.nextLine();
        System.out.println("Reversed string is: " + reverseString(str));
        sc.close();
    }
    static String reverseString(String str){
        if (str.isEmpty())
            return str;
        return reverseString(str.substring(1)) + str.charAt(0);
    }
}

This program demonstrates how to reverse a string using recursion in Java.

Use Case:

This method is useful for understanding recursion concepts or solving problems where recursion is explicitly required. However, for larger strings, iterative approaches (like using a loop) may be more efficient.

  1. Input:

    • The program takes a string input from the user using Scanner.
  2. Recursive Method:

    • reverseString(String str):
      • Base Case: If the string is empty (str.isEmpty()), return the string itself (empty string). This terminates the recursion.
      • Recursive Step:
        • str.substring(1): Extracts the substring starting from the second character.
        • str.charAt(0): Gets the first character of the string.
        • The method appends the first character to the reversed result of the rest of the string (processed recursively).
  3. Working of Recursion:

    • The recursion breaks the string into smaller substrings until it becomes empty.
    • As the recursion unwinds, it builds the reversed string by appending characters in reverse order.
  4. Execution:

    • For example, if the input is "hello", the recursion works as follows:
      reverseString("hello") -> reverseString("ello") + 'h'
      reverseString("ello") -> reverseString("llo") + 'e'
      reverseString("llo") -> reverseString("lo") + 'l'
      reverseString("lo") -> reverseString("o") + 'l'
      reverseString("o") -> reverseString("") + 'o'
      reverseString("") -> ""
      
      The result is "olleh".

Key Features:

  • Recursion:

    • The method repeatedly reduces the problem size until the base case is reached.
    • It is a compact and elegant way to reverse a string but might not be the most efficient for long strings due to stack depth limitations.
  • Immutable Strings:

    • Java strings are immutable, so the recursive method creates new substrings during each call, making this method memory-intensive for large strings.

Output

Enter a string:
welcome to oodlescoop
Reversed string is: poocseldoo ot emoclew