Java Recursive Method: Reverse a given string
Java Recursive: Exercise-6 with Solution
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:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/java-exercises/recursive/java-recursive-exercise-6.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics