Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

Reverse a String in Java Using Recursion – Step‑by‑Step Guide

Reverse a String in Java Using Recursion

Recursion is a powerful technique for solving problems that can be broken down into smaller, similar sub‑problems. Reversing a string is a classic example that demonstrates how a simple recursive function can elegantly handle string manipulation.

Why Use Recursion?

Java Implementation

The following program reads a string, applies a recursive reversal method, and prints the result.

package com.guru99;

public class ReverseString {
    public static void main(String[] args) {
        String myStr = "Guru99";
        String reversed = reverseString(myStr);
        System.out.println("The reversed string is: " + reversed);
    }

    /**
     * Recursively reverses the given string.
     * @param str the string to reverse
     * @return the reversed string
     */
    public static String reverseString(String str) {
        if (str.isEmpty()) {
            return ""; // Base case: an empty string is its own reverse
        }
        // Recurse on the substring that excludes the first character
        return reverseString(str.substring(1)) + str.charAt(0);
    }
}

Typical Output

The reversed string is: 99uruG

Understanding the Flow

The recursion works by repeatedly stripping the first character and appending it to the result of the reverse of the remaining substring. When the substring becomes empty, the recursion unwinds, concatenating characters in reverse order.

Edge Cases & Performance

Takeaway

Recursive string reversal is concise and showcases core algorithmic thinking. For production code where performance is critical, an iterative approach or using a {@code StringBuilder} is preferable due to lower stack usage.

Java

  1. Mastering Java Strings: Creation, Methods, and Best Practices
  2. Java Recursion: Understanding, Examples, and Trade‑Offs
  3. Mastering String Representations in Java Enums
  4. Java String length() Method: How to Get a String’s Size (Example)
  5. Mastering Java's String compareTo() Method: Syntax, Use Cases, and Practical Examples
  6. Easily Convert Strings to Integers in Java: A Step‑by‑Step Guide
  7. Mastering Java's split() Method: A Practical Guide with Code Examples
  8. Converting a Char to a String in Java – Practical Examples and Best Practices
  9. Generate Fibonacci Sequence in Java: For, While, and Recursive Examples
  10. Java 8 Overview: New Functional, Streaming, and Date-Time APIs