Java Examples
Java ExamplesPrograms with output

Java Program to Reverse a Number


Example:
import java.util.Scanner;

public class ReverseNumber {
   public static void main(String args[]) {
      int num, rev = 0;

      System.out.println("Enter a number to reverse: ");
      Scanner in = new Scanner(System.in);
      num = in.nextInt();

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

      System.out.println("Reversed Number: " + rev);
   }
}
Output:
Enter a number to reverse: 
Reversed Number: 54321

This reverse number program prompts the user to enter a number, then uses a while loop to reverse the digits of the number. Inside the loop, the program extracts the last digit of the number using the modulus operator, and adds it to the reversed number. It then removes the last digit from the original number by dividing it by 10. The loop continues until the original number becomes 0.

Finally, the program prints the reversed number to the console.

Program explanation (Reverse number)

1. First, we import the Scanner class from the java.util package to allow us to read input from the user.

Example:
import java.util.Scanner;

2. We define a public class called ReverseNumber that contains the main method, which is the entry point of the program.

Example:
public class ReverseNumber {
   public static void main(String args[]) {
      // code goes here
   }
}

3. Inside the main method, we declare two integer variables: num, which will hold the number entered by the user, and rev, which will hold the reversed number. We initialize rev to 0.

Example:
int num, rev = 0;

4. We prompt the user to enter a number and read it from the console using the Scanner class.

Example:
System.out.println("Enter a number to reverse: ");
Scanner in = new Scanner(System.in);
num = in.nextInt();

5. We use a while loop to reverse the digits of the number. Inside the loop, we extract the last digit of the number using the modulus operator (num % 10) and add it to the reversed number (rev = rev * 10 + digit). We then remove the last digit from the original number by dividing it by 10 (num = num / 10). The loop continues until the original number becomes 0.

Example:
while(num != 0) {
   int digit = num % 10;
   rev = rev * 10 + digit;
   num = num / 10;
}

6. Finally, we print the reversed number to the console using the System.out.println method.

Example:
System.out.println("Reversed Number: " + rev);

That’s it! When you run this program, it will prompt you to enter a number, then print the reversed number to the console.


Share this page on:

Was this page helpful ?

Let us know how we did!

Subscribe Email Updates

to get latest update