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

Check if a number is palindrome or not is one of the common java interview question.

Palindrome number is a number where number remain the same when reversed.

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

In the below example first user enters a number using nextInt() method of Scanner class. This number is stored in ‘number’ variable.

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 in while loop ‘number’ variable is looped until it is equal to zero.

In each iteration of while loop 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.

If it is equal it a palindrome number else it is not a palindrome number.

Now let’s see program to check if 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