Palindrome Checker Program in Java
This program checks if a given number is a palindrome. A palindrome is a number that remains the same when its digits are reversed.
Program Structure
The program is structured into the following parts:
- Class Definition: The class
PalindromeChecker
contains the main method and a helper method. - Main Method: The
main
method reads input from the user and calls the helper method to check if the number is a palindrome. - Helper Method: The
isPalindrome
method checks if the given number is a palindrome.
Java Code
/**
* This class contains a method to check if a given number is a palindrome.
*/
public class PalindromeChecker {
/**
* Main method to execute the palindrome check.
* @param args Command-line arguments (not used).
*/
public static void main(String[] args) {
java.util.Scanner scanner = new java.util.Scanner(System.in);
System.out.println("Enter a number to check if it is a palindrome: ");
int number = scanner.nextInt();
scanner.close();
if (isPalindrome(number)) {
System.out.println(number + " is a palindrome.");
} else {
System.out.println(number + " is not a palindrome.");
}
}
/**
* Method to check if a given number is a palindrome.
* @param number The number to check.
* @return true if the number is a palindrome, false otherwise.
*/
public static boolean isPalindrome(int number) {
int originalNumber = number;
int reversedNumber = 0;
// Reverse the digits of the number
while (number != 0) {
int digit = number % 10;
reversedNumber = reversedNumber * 10 + digit;
number /= 10;
}
// Check if the original number is equal to the reversed number
return originalNumber == reversedNumber;
}
}
Explanation
The PalindromeChecker
class includes a main
method and a isPalindrome
method.
- The
main
method starts by creating aScanner
object to read user input. It prompts the user to enter a number and stores the input in the variablenumber
. - The
isPalindrome
method is then called with the user-provided number. If the method returnstrue
, the number is a palindrome; otherwise, it is not. - The
isPalindrome
method works by reversing the digits of the given number and comparing the reversed number to the original number. If they are the same, the number is a palindrome.