Java Online Compiler
Example: Reverse String Using Recursion in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Reverse String Using Recursion public class Main { /** * Recursively reverses the input string. * * @param str The string to be reversed. * @return The reversed string. */ public static String reverseStringRecursive(String str) { // Step 1: Define the base case. // If the string is empty or has only one character, it's already reversed. if (str == null || str.isEmpty() || str.length() == 1) { return str; } // Step 2: Define the recursive step. // Call the function for the substring starting from the second character, // then concatenate the first character to the end of the result. return reverseStringRecursive(str.substring(1)) + str.charAt(0); } public static void main(String[] args) { // Step 3: Test the recursive function with an example string. String originalString1 = "hello"; String reversedString1 = reverseStringRecursive(originalString1); System.out.println("Original String: \"" + originalString1 + "\""); System.out.println("Reversed String: \"" + reversedString1 + "\""); // Test with another string String originalString2 = "recursion"; String reversedString2 = reverseStringRecursive(originalString2); System.out.println("\nOriginal String: \"" + originalString2 + "\""); System.out.println("Reversed String: \"" + reversedString2 + "\""); // Test with an empty string String originalString3 = ""; String reversedString3 = reverseStringRecursive(originalString3); System.out.println("\nOriginal String: \"" + originalString3 + "\""); System.out.println("Reversed String: \"" + reversedString3 + "\""); // Test with a null string String originalString4 = null; String reversedString4 = reverseStringRecursive(originalString4); System.out.println("\nOriginal String: " + originalString4); System.out.println("Reversed String: " + reversedString4); } }
Output
Clear
ADVERTISEMENTS