You are here

Java program to reverse a number

Java program to find reverse of a number, i.e., if input is 951 then the output will be 159.

Java programming source code

  1. import java.util.Scanner;
  2.  
  3. class ReverseNumber
  4. {
  5.    public static void main(String args[])
  6.    {
  7.       int n, reverse = 0;
  8.          
  9.       System.out.println("Enter an integer to reverse");
  10.       Scanner in = new Scanner(System.in);
  11.       n = in.nextInt();
  12.          
  13.       while(n != 0)
  14.       {
  15.           reverse = reverse * 10;
  16.           reverse = reverse + n%10;
  17.           n = n/10;
  18.       }
  19.        
  20.       System.out.println("Reverse of the number is " + reverse);
  21.    }
  22. }

Download Reverse number program class file.

Output of program:
reverse number

You can also reverse or invert a number using recursion. You can use this code to check if a number is a palindrome number or not, if on reversing a number we get the same number then it's a palindrome number otherwise not.