Write a Java Program to Reverse a Number

Reversing a number in Java can be done by breaking it down into individual digits and then rearranging them in reverse order.

Here’s a simple Java program that demonstrates this process:

import java.util.Scanner;

public class ReverseNumber {
   public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      int num = input.nextInt();
      int reversed = 0;

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

      System.out.println("Reversed Number: " + reversed);
   }
}

This program takes an integer input from the user using the Scanner class, and then initializes a variable called reversed to zero.

The program then enters a while loop that continues until the input number is completely broken down into individual digits.

Within the while loop, the program uses the modulus operator (%) to get the remainder of the input number divided by 10.

This gives us the rightmost digit of the input number.

The program then multiplies the current value of reversed by 10 and adds the rightmost digit to it.

This shifts the current digits of reversed one place to the left and adds the rightmost digit to the right side of reversed.

Finally, the program divides the input number by 10 to discard the rightmost digit, and the loop continues until all the digits have been processed.

Once the loop completes, the value of reversed is the reverse of the original input number, and this value is printed to the console using the System.out.println() method.

Overall, this is a simple and efficient way to reverse a number in Java.