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

Run it Now
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("\nAfter reverse string  : " + revstr);

    }
}

Output:

Enter a String : cbb
After reverse string  : bbc