# Reverse the Digits of a Number Using Recursion | Java Example

by Dinesh Thakur Category: Java Methods

In this program, user is asked a number to enter which is stored in integer form in variable n. The value entered is say 1023.Now, this value of variable n is passed to parameter x by invoking revers() method. In revers() method, x is divided by 10 and the remainder is displayed (% returns remainder). When 1023 is divided by 10, the remainder will be 3 which is displayed on the screen. Then, again revers() is invoked with value 102/10 i.e. with 102 (because the output of dividing two integers is also an integer). 102 is assigned to variable x. Again, 102 is divided by 10 and the remainder is displayed. The remainder this time will be 2 which is displayed. Again revers() method is invoked with 10/10 i.e. which 1. And the process continues until value of x becomes 0.

Here is the Java Example for ReverseDigits:

```import java.io.*;

class ReverseDigits

{

void revers(int x)

{

if(x==0) return;

else

{

System.out.print(x%10);

revers(x/10);

}

}

public static void main(String args[])

throws IOException

{

ReverseDigits Digit = new ReverseDigits();

String h;

int n;

System.out.print("Enter a number to Reverse : ");

n=Integer.parseInt(h);

System.out.print("The  Reverse Number is : ");

Digit.revers(n);

}

}

```  Dinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles