Java program to check if a number is palindrome or not

Let’s learn java program to check if a number is palindrome or not.

Java program to check if a number is palindrome or not

A palindrome number is a number which when reversed remains the same.

For example: 141, 101, 181, 12321 etc..

To check if a number is palindrome or not first user enters a number using nextInt() method of Scanner class. This number is stored in ‘number’ variable.

Now this ‘number’ variable value is stored in ‘givenNumber’ variable. Because at the end we have to compare values of ‘reversedNumber’ variable and ‘givenNumber’ variable.

Then using while loop ‘number’ variable is looped until it is equal to zero. In each iteration last digit of ‘number’ variable is stored in ‘remainder’ variable.

Then remainder is added to reversedNumber in such a way that it is added to next place value. In the next step last digit is removed from ‘number’ variable after dividing by 10.

Finally ‘givenNumber’ and ‘reversedNumber’ is compared using if else. If it is equal then it is a palindrome number else it is not a palindrome number. Now let’s see program to check whether a number is palindrome or not.

import java.util.Scanner;
public class PalindromeNumberInJava
{
   public static void main(String[] args)
   {
      int remainder, reversedNumber = 0, givenNumber;
      System.out.println("Please enter a number: ");
      Scanner sc = new Scanner(System.in);
      int number = sc.nextInt();
      givenNumber = number;
      while(number != 0)
      {
         remainder = number % 10;
         reversedNumber = reversedNumber * 10 + remainder;
         number /= 10;
      }
      if(givenNumber == reversedNumber)
      {
         System.out.println(givenNumber + " is a palindrome number.");
      }
      else
      {
         System.out.println(givenNumber + " not a palindrome number.");
      }
      sc.close();
   }
}

Output:

java program to check if a number is palindrome or not