Hero Background

Next-Gen App & Browser Testing Cloud

Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Next-Gen App & Browser Testing Cloud

Write a Java program to print the entered number in reverse?

To print an entered number in reverse in Java, read the integer with the Scanner class, then loop while the number is greater than zero. On each pass, take the last digit with the modulo operator (number % 10), append it to the result using reversed = reversed * 10 + digit, and remove that digit with integer division (number / 10). When the loop ends, the result holds the digits in reverse order. The same idea also works with StringBuilder, and a few extra lines handle negative numbers and large values safely.

How Reversing a Number Works

Reversing an integer is a repeating cycle of three arithmetic steps. You peel off the rightmost digit, slot it onto the growing result, and shrink the original number until nothing is left.

  • Extract the last digit: number % 10 divides the number by 10 and returns the remainder, which is always the rightmost digit.
  • Build the reversed value: reversed = reversed * 10 + digit shifts the existing result one place to the left and drops the new digit into the ones place.
  • Drop the processed digit: number = number / 10 uses integer division to discard the digit you just handled.
  • Repeat until empty: the loop continues while number != 0, so each iteration moves one digit from the input to the output.

Java Program to Reverse a Number Using a while Loop

The program below reads a number from the user with Scanner and reverses it with the arithmetic cycle described above. It compiles and runs on any standard JDK.

import java.util.Scanner;

public class ReverseNumber {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number you want to reverse: ");
        int number = scanner.nextInt();

        int reversed = 0;
        while (number != 0) {
            int digit = number % 10;        // extract the last digit
            reversed = reversed * 10 + digit; // append it to the result
            number = number / 10;            // remove the last digit
        }

        System.out.println("Reversed number is " + reversed);
        scanner.close();
    }
}

Running the program and entering 12345 produces:

Enter the number you want to reverse: 12345
Reversed number is 54321

Step-by-Step Walkthrough

Tracing the loop for the input 12345 makes the pattern clear. Each row shows one iteration: the digit pulled out, the value of reversed after appending it, and what remains of number.

Iterationnumber % 10 (digit)reversednumber / 10
1551234
2454123
3354312
4254321
51543210

Once number hits 0, the loop condition fails and the final value of reversed is the answer. Note that an entry like 100 reverses to 1, because the trailing zeros become leading zeros and an int does not keep leading zeros.

Handling Negative Numbers

The basic loop assumes a positive number. To support negatives cleanly, remember the sign, reverse the absolute value, then re-apply the sign. This avoids the surprises that come from how the modulo operator behaves with negative operands.

import java.util.Scanner;

public class ReverseSignedNumber {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number you want to reverse: ");
        int number = scanner.nextInt();

        boolean negative = number < 0;
        number = Math.abs(number);

        int reversed = 0;
        while (number != 0) {
            reversed = reversed * 10 + number % 10;
            number = number / 10;
        }

        if (negative) {
            reversed = -reversed;
        }

        System.out.println("Reversed number is " + reversed);
        scanner.close();
    }
}

Entering -678 now gives:

Enter the number you want to reverse: -678
Reversed number is -876

Alternative: Reverse Using StringBuilder

If you prefer not to write the loop yourself, convert the number to a String and call the built-in reverse() method on StringBuilder. It is concise and easy to read.

import java.util.Scanner;

public class ReverseWithStringBuilder {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number you want to reverse: ");
        int number = scanner.nextInt();

        String reversed = new StringBuilder(String.valueOf(number)).reverse().toString();

        System.out.println("Reversed number is " + reversed);
        scanner.close();
    }
}

Entering 1234 prints:

Enter the number you want to reverse: 1234
Reversed number is 4321

This approach keeps the result as a String, which preserves any leading zeros visually. Be aware that for a negative input such as -45, the minus sign moves to the end (54-), so the arithmetic method is the better choice when the sign matters.

Watch Out for Integer Overflow

An int in Java can hold values only up to Integer.MAX_VALUE, which is 2,147,483,647. Reversing a large number can push the result past that limit and silently produce a wrong answer. For example, reversing 1000000003 should give 3000000001, which is out of range for an int. Using a long accumulator gives you the headroom to detect or store the larger value safely.

import java.util.Scanner;

public class ReverseWithOverflowGuard {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number you want to reverse: ");
        int number = scanner.nextInt();

        long reversed = 0;
        while (number != 0) {
            reversed = reversed * 10 + number % 10;
            number = number / 10;
        }

        if (reversed > Integer.MAX_VALUE || reversed < Integer.MIN_VALUE) {
            System.out.println("Reversed value " + reversed + " overflows the int range.");
        } else {
            System.out.println("Reversed number is " + reversed);
        }
        scanner.close();
    }
}

Entering 1000000003 produces:

Enter the number you want to reverse: 1000000003
Reversed value 3000000001 overflows the int range.

Best Practices

  • Pick the loop method for control: the arithmetic while loop runs in O(log10 n) time with constant extra space, and it makes the sign and overflow logic easy to add.
  • Reach for StringBuilder for readability: when input is always non-negative and clarity matters more than micro-optimization, the one-line StringBuilder version is hard to beat.
  • Guard the integer range: use a long accumulator or an explicit bounds check whenever the input can be large enough to overflow an int.
  • Validate user input: wrap scanner.nextInt() in a check or try-catch so a non-numeric entry does not throw an InputMismatchException.
  • Close the Scanner: call scanner.close() when you are done reading to release the underlying input stream.

Small programs like this are the building blocks of larger Java test suites. When those suites grow into UI or browser automation, you can run them across thousands of browser and OS combinations on the Selenium Automation grid at TestMu AI to confirm your logic behaves the same everywhere.

Frequently Asked Questions

How do you reverse a number in Java without using a loop?

Convert the number to a String and use StringBuilder: new StringBuilder(String.valueOf(number)).reverse().toString(). This avoids an explicit loop, but for negative values the minus sign ends up at the end of the string, so the arithmetic while-loop method is safer for signed input.

Why does reversing 100 give 1 instead of 001 in Java?

An int has no concept of leading zeros. When you reverse 100, the trailing zeros become leading zeros, and 001 is simply the integer 1. If you need to preserve the zeros visually, treat the number as a String instead of an int.

How does the modulo operator help reverse a number?

number % 10 returns the last digit of the number. You append that digit to the result with reversed = reversed * 10 + digit, then drop the digit with number = number / 10. Repeating this until the number reaches zero rebuilds the digits in reverse order.

How do you reverse a negative number in Java?

Record the sign, reverse the absolute value with Math.abs(number), then re-apply the sign to the result. For example, -678 becomes -876. Reversing the raw negative value directly is error-prone because of how the modulo operator behaves with negative operands.

Can reversing a number cause integer overflow in Java?

Yes. If the reversed value exceeds Integer.MAX_VALUE (2,147,483,647), an int silently overflows and produces a wrong result. Reversing 1000000003 gives 3000000001, which is out of range. Use a long accumulator or add an explicit overflow check to handle this safely.

Which approach is faster for reversing a number in Java?

The arithmetic while-loop method is the most efficient. It runs in O(log10 n) time and uses constant extra space because it works directly on the integer. The StringBuilder method is just as readable but allocates a String and a StringBuilder, so it uses more memory.

Related Questions

Test Your Website on 3000+ Browsers

Get 100 minutes of automation test minutes FREE!!

Test Now...

KaneAI - Testing Assistant

World’s first AI-Native E2E testing agent.

...

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests