English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input Output (I/O)/O)

Java Reader/Writer

Java other topics

Java program to reverse numbers

Comprehensive Java Examples

In this program, you will learn how to reverse numbers using while loop and for loop in Java.

Example: Reversing numbers using while loop in Java

public class ReverseNumber {
    public static void main(String[] args) {
        int num = 1234, reversed = 0;
        while(num != 0) {
            int digit = num % 10;
            reversed = reversed * 10 + digit;
            num /= 10;
        }
        System.out.println("Reversed number: " + reversed);
    }
}

When running the program, the output is:

Reversed number: 4321

In this program, the while loop is used to reverse the number by the following steps:

  • First, divide num by10The remainder is stored in the variable digit. Now, digit contains the last digit of num, that is4and then multiply digit by10and then add it to the reversed variable. Multiply10A new position will be added in the reversed number. Multiply one-tenth by10The tenth digit can be obtained, the hundredth digit can be obtained by multiplying by one-tenth, and so on. In this case, reversed contains 0 * 10 + 4 =4.
    Then num is divided by10, so now it only contains the first three digits:123.

  • After the second iteration, digit equals3, reversed equals4 * 10 + 3 = 43and num= 12

  • After the third iteration, digit equals2, reversed equals43 * 10 + 2 = 432and num= 1

  • After the fourth iteration, digit equals1, reversed equals432 * 10 +1 = 4321and num=0

  • Now num=0, so the test expression num != 0 fails and the while loop exits. reversed already contains the reversed digits4321.

Example2Using for loop to reverse numbers in Java

public class ReverseNumber {
    public static void main(String[] args) {
        int num = 1234567, reversed = 0;
        for (; num != 0; num /= 10) {
            int digit = num % 10;
            reversed = reversed * 10 + digit;
        }
        System.out.println("Reversed Number: ", + reversed);
    }
}

When running the program, the output is:

Reversed Number: 7654321

In the above program, the while loop is replaced by the for loop, where:

  • Without using the initialization expression

  • The test expression remains unchanged (num != 0)

  • Update/The increment expression contains num /= 10.

Therefore, after each iteration, the update expression will run, thus deleting the last digit num.

When the for loop exits, reversed will contain the reversed numbers.

Comprehensive Java Examples