Write a program to check whether number entered through keyboard is palindrome or not.

here is a Java program that checks whether a number entered through the keyboard is a palindrome or not:

				
					import java.util.Scanner;

public class PalindromeCheck {
    public static void main(String[] args) {
        // Create a Scanner object to read input from the user
        Scanner scanner = new Scanner(System.in);

        // Prompt the user to enter a number
        System.out.print("Enter an integer: ");
        int num = scanner.nextInt();

        // Store the original number
        int originalNum = num;
        int reversedNum = 0;
        int remainder;

        // Reverse the number
        while (num != 0) {
            remainder = num % 10;
            reversedNum = reversedNum * 10 + remainder;
            num /= 10;
        }

        // Check if the original number is equal to its reverse
        if (originalNum == reversedNum) {
            System.out.println(originalNum + " is a palindrome.");
        } else {
            System.out.println(originalNum + " is not a palindrome.");
        }

        // Close the scanner
        scanner.close();
    }
}

				
			

Explanation

  1. Importing Scanner Class: The Scanner class from java.util package is imported to read input from the user.
  2. Creating Scanner Object: A Scanner object named scanner is created to read input from the standard input stream (keyboard).
  3. Prompt User for Input: The program prompts the user to enter a number.
  4. Read the Input: The entered number is read and stored in the variable num.
  5. Store Original Number: The original number is stored in the variable originalNum for later comparison.
  6. Reverse the Number: A while-loop is used to reverse the digits of the number:
    • The remainder of the number when divided by 10 is obtained.
    • This remainder is used to build the reversed number.
    • The original number is divided by 10 to remove the last digit.
  7. Check Palindrome: The program checks if the reversed number is equal to the original number.
  8. Print Result: Based on the comparison, the program prints whether the number is a palindrome or not.
  9. Close the Scanner: The scanner object is closed to free the associated resources.

Sample Output

Example 1: Palindrome Number

				
					Enter an integer: 121
121 is a palindrome.

				
			

Example 2: Not a Palindrome Number

				
					Enter an integer: 123
123 is not a palindrome.

				
			

This Java program reads an integer from the user, reverses the digits of the number, and checks if the reversed number is the same as the original. If they are the same, it prints that the number is a palindrome; otherwise, it prints that the number is not a palindrome.

Scroll to Top