Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Reverse a Number in Java

Reverse integer digits in Java using % 10, division, and a long accumulator. Scanner reads an int; trailing zeros disappear and negative signs remain.

BeginnerJava Loop ProgramsExample 5 of 25
reverse-a-number.java
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Enter a number: ");
7 int n = sc.nextInt();
8
9 long rev = 0;
10 while (n != 0) {
11 int d = n % 10;
12 rev = rev * 10 + d;
13 n /= 10;
14 }
15
16 System.out.println("Reversed number = " + rev);
17 sc.close();
18 }
19}

Sample Output

Enter a number: 1234
Reversed number = 4321

The extracted digits are 4,3,2,1. rev becomes 4,43,432,4321 while n becomes 123,12,1,0.

In this one

  • Extract and remove a last digit
  • Append a digit numerically
  • Understand lost leading zeros

How it works

  1. 1

    Read n.

  2. 2

    Start rev at zero.

  3. 3

    Extract d, update rev, and divide n by ten.

  4. 4

    Repeat until n is zero, then print rev.

Edge cases

Trailing zero

Enter 1200

The reverse is the number 21, not the text 0021.

Negative input

Enter -123

Java remainder and division keep the digit process signed, so this code produces -321.

What's going on

Build a number whose digits appear in reverse order. Input 1234 becomes 4321. This is useful for practising how a loop can take apart one value and construct another, without treating the input as text.

Scanner is the keyboard reader. The % operator gives the remainder after division, so n % 10 selects the last digit. The expression rev * 10 + d shifts the saved reverse one place and appends that digit. Whole-number division n /= 10 then removes the digit from the working input.

The loop ends when n becomes zero. Notice that n itself is consumed here, unlike the palindrome program, which needs the original later. Trailing zeros in the input become leading zeros and disappear in a numeric result. A long is used for rev so reversing a valid int does not exceed the result type. Negative inputs keep a negative sign in this implementation.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What is the numeric reverse of 120?

Pick an answer to check it.

Question 2

What removes the last digit?

Pick an answer to check it.

Questions people ask

Why multiply the reverse by 10?

It creates a new ones position for the next extracted digit.

Can I print n after the loop to get the original?

No. This version reduces n to zero. Save a copy first if you need it.

Why use long for rev?

A reversed int can be bigger than the largest positive int, even if the input itself fits.