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 { // Recursive method to reverse a string public static String reverseStringRecursive(String str) { // Step 1: Base case: if the string is null, empty, or has one character, return it if (str == null || str.isEmpty() || str.length() == 1) { return str; } // Step 2: Recursive step: take the last character and prepend it to the // reversed string of the substring excluding the last character. // Or, take the first character and append it after the reversed rest of the string. // We'll use the latter for simpler implementation. return reverseStringRecursive(str.substring(1)) + str.charAt(0); } public static void main(String[] args) { // Step 1: Define the original string String originalString = "hello"; // Step 2: Call the recursive method to reverse the string String reversedString = reverseStringRecursive(originalString); // Step 3: Print the original and reversed strings System.out.println("Original String: " + originalString); System.out.println("Reversed String: " + reversedString); } }
Output
Clear
ADVERTISEMENTS