Write a Program to Check Given Number is a Palindrome or Not


This Java program checks whether an input integer is a palindrome or not. A palindrome number is a number that remains the same when its digits are reversed.

  • The program starts by using a Scanner object to read in an integer from the user. It then initializes some variables: rev to store the reversed integer, rem to store the remainder of the input integer when it is divided by 10, and temp to store a copy of the input integer.
  • The program then uses a while loop to reverse the input integer by extracting each digit one by one, adding it to rev multiplied by 10, and then dividing the input integer by 10 to remove the last digit. This continues until the input integer is reduced to 0.
  • Finally, the program checks whether the original input integer (temp) is equal to the reversed integer (rev). If they are equal, then the program prints that the input integer is a palindrome. Otherwise, it prints that the input integer is not a palindrome.

Overall, this program correctly checks whether an input integer is a palindrome or not. However, it could be improved by handling the case where the user inputs a negative integer. In this case, the program would print out that the negative integer is not a palindrome, even though it technically is a palindrome when its absolute value is considered. A message should be added to handle this case.

Source Code

import java.util.Scanner;
class Palindrome_Number
{
	public static void main (String[]args)
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter The Digits :");
		int num = input.nextInt();
		int rev = 0, rem, temp;
		temp = num;
		while (num != 0)
		{
			rem = num % 10;
			rev = rev * 10 + rem;
			num /= 10;
		};
 
		if (temp == rev)
			System.out.println (temp + " is Palindrome");
		else
			System.out.println (temp + " is not Palindrome");
	}
}

Output

Enter The Digits :68586
68586 is Palindrome

Enter The Digits :67587
67587 is not Palindrome

Example Programs