Java Program to reverse a string using recursion


In this program, you will learn how to reverse a string using recursion in java.


cbb => bbc

ABCD => DCBA

Example: How to reverse a string using recursion in java.

import java.util.Scanner;

class Main {

    String reverseString(String str) {

        if (str.isEmpty())
            return str;

        return reverseString(str.substring(1)) + str.charAt(0);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a string:");
        String str = sc.nextLine();

        Main obj = new Main();
        String revstr = obj.reverseString(str);

        System.out.println("After reverse string:" + revstr);

    }
}

Output:

Enter a string:Xiith
After reverse string:htiiX