;

# Java Program to Reverse a Number

###### Tutorialsrack 26/06/2021 Java

In this Java program, you’ll learn how to reverse a number. This post explains two ways to reverse a number: `while `and `for` loop

Here are the examples to reverse a number in Java.

Algorithm to reverse digits of a number

• Get the least significant digit(rightmost digit or last digit) of the number.
`digit = num%10;`
• Append it at the end of the reverse number.
`reversedNum  = (reversedNum * 10) + digit;`
• Remove the rightmost digit from the number.
`num = num/10;`
• Repeat this process till the number is greater than zero.

### Example 1: Java Program to Reverse a Number using While Loop

In this program, you will see how to reverse a number using a `while` loop.

##### Example 1: Java Program to Reverse a Number using While Loop
``````//Java Program to Reverse a Number using While Loop

import java.util.Scanner;

public class JavaPrograms {

public static void main(String[] args) {

int reversedNum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int num = sc.nextInt();

// closing scanner class(not compulsory, but good programming practice)
sc.close();

// run loop until num becomes 0
while (num != 0) {

// get last digit from num
int digit = num % 10;
reversedNum = reversedNum * 10 + digit;

// remove the last digit from num
num /= 10;
}

System.out.println("Reversed Number: " + reversedNum);
}
}
``````
##### Output

Enter a number:

5245

Reversed Number: 5425

### Example 2: Java Program to Reverse a Number using For Loop

In this program, you will see how to reverse a number using a `for` loop.

##### Example 2: Java Program to Reverse a Number using For Loop
``````//Java Program to Reverse a Number using For Loop

import java.util.Scanner;

public class JavaPrograms {

public static void main(String[] args) {

int reversedNum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int num = sc.nextInt();

// closing scanner class(not compulsory, but good programming practice)
sc.close();

for (; num != 0; num /= 10) {
int digit = num % 10;
reversedNum = reversedNum * 10 + digit;
}

System.out.println("Reversed Number: " + reversedNum);
}
}
``````
##### Output

Enter a number:

85658541

Reversed Number: 14585658