Java Program to reverse a number using recursion


In this program, You will learn how to reverse a number using recursion in java.


123 => 321

456 => 654

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

import java.util.Scanner;

class Main {

    int rev = 0, r;

    int reverseNumber(int num) {
        if (num == 0) {
            return rev;
        }

        if (num > 0) {
            r = num % 10;
            rev = rev * 10 + r;
            num = reverseNumber(num / 10);
        }

        return rev;
    }

    public static void main(String[] args) {
        int num, rev;
        Scanner sc = new Scanner(System.in);
        Main obj = new Main();

        System.out.print("Enter a number:");
        num = sc.nextInt();

        rev = obj.reverseNumber(num);
        System.out.println("After reverse number is:" + rev);

    }
}

Output:

Enter a number:123
After reverse number is:321