1. Introduction
Reversing a string is a common programming task. This Java program demonstrates how to reverse a string using recursion, a process in which a function calls itself directly or indirectly.
2. Program Steps
1. Define a class named ReverseString.
2. Define a recursive method reverse inside the class that takes a string and returns its reverse.
a. If the length of the string is 0 or 1, return the string itself.
b. Otherwise, call the reverse method with the substring (excluding the first character) and concatenate the first character at the end.
3. Inside the main method, define a string that needs to be reversed.
4. Call the reverse method and print the reversed string.
3. Code Program
public class ReverseString { // Step 1: Define a class named ReverseString
// Step 2: Define a recursive method reverse that takes a string and returns its reverse
public static String reverse(String str) {
if (str.isEmpty()) // Step 2a: If the length of the string is 0, return the string itself
return str;
// Step 2b: Call the reverse method with the substring (excluding the first character) and concatenate the first character at the end
return reverse(str.substring(1)) + str.charAt(0);
}
public static void main(String[] args) { // Main method
String str = "Java"; // Step 3: Define a string that needs to be reversed
String reversed = reverse(str); // Step 4: Call the reverse method and store the reversed string
System.out.println("Original String: " + str);
System.out.println("Reversed String: " + reversed); // Print the reversed string
}
}
Output:
Original String: Java Reversed String: avaJ
4. Step By Step Explanation
– Step 1: A class named ReverseString is defined.
– Step 2: A method named reverse is defined. This method takes a string as a parameter and returns its reverse using recursion.
– Step 2a: If the string is empty, it returns the string itself.
– Step 2b: If the string is not empty, it calls itself with the substring (excluding the first character) and concatenates the first character at the end.
– Step 3: Inside the main method, a string str is defined which needs to be reversed.
– Step 4: The reverse method is called with the string str as the argument and the result is printed. The output shows the original string as "Java" and the reversed string as "avaJ".