w3resource

Java Recursive Method: Reverse a given string


Recursive String Reversal

Write a Java recursive method to reverse a given string.

Sample Solution:

Java Code:

public class StringReverser {

  public static String reverseString(String str) {
    // Base case: if the string is empty or has only one character, it is already reversed
    if (str.isEmpty() || str.length() == 1) {
      return str;
    }

    // Recursive case: reverse the substring starting from the second character and concatenate the first character
    return reverseString(str.substring(1)) + str.charAt(0);
  }

  public static void main(String[] args) {
    String input = "Java, World!";
    String reversed = reverseString(input);
    System.out.println("Original string: " + input);
    System.out.println("Reversed string: " + reversed);
  }
}

Sample Output:

Original string: Java, World!
Reversed string: !dlroW ,avaJ

Explanation:

In the above exercises -

First, we define a class "StringReverser" that includes a recursive method reverseString() to reverse a given string str.

The reverseString() method has two cases:

  • Base case: If the string is empty or has only one character, it is already reversed, so we return the original string.
  • Recursive case: For any string with length greater than 1, we recursively reverse the substring starting with the second character and concatenate the first character at the end. This process continues until the string is reduced to an empty string or one character.

In the main() method, we demonstrate the reverseString() method by reversing the string "Java, World!" and printing both the original and reversed strings.

Flowchart:

Flowchart: Java  recursive Exercises: Reverse a given string.

For more Practice: Solve these Related Problems:

  • Write a Java program to recursively reverse a string without using extra helper methods.
  • Write a Java program to recursively reverse a string and then compare it with the original to check for palindromicity.
  • Write a Java program to recursively reverse the order of words in a sentence while preserving the order of characters in each word.
  • Write a Java program to recursively reverse a string by swapping its first and last characters until the string is fully reversed.

Java Code Editor:

Java Recursive Previous: Calculate Base to Power.
Java Recursive Next: Find the greatest common divisor.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.