// JAVA PROGRAM TO DEMONSTRATE THE PALINDROME PROGROM USING CLASSES AND OBJECT.
class PalindromeExample {
public static void main(String args[]) {
int remainder, reversedNumber = 0, originalNumber; // Declare variables for storing digits
int numberToCheck = 454; // The number to be checked for palindrome
originalNumber = numberToCheck; // Store the original number for later comparison
// Reverse the digits of the number
while (numberToCheck > 0) {
remainder = numberToCheck % 10; // Extract the last digit
reversedNumber = (reversedNumber * 10) + remainder; // Build the reversed number
numberToCheck = numberToCheck / 10; // Remove the last digit
}
// Check if the reversed number is equal to the original number
if (originalNumber == reversedNumber) {
System.out.println("The number is a palindrome."); // Print if it's a palindrome
} else {
System.out.println("The number is not a palindrome."); // Print if it's not a palindrome
}
}
}
OUTPUT:-
palindrome number
Explanation of the code:
- The code defines a class named PalindromeExample.
- Inside the class, there's the main method which serves as the entry point of the program.
- The program aims to check whether a given number (n initialized as 454) is a palindrome or not. A palindrome is a number that reads the same forwards and backwards.
- temp is used to store the original number so that we can compare it with the reversed number later.
- The while loop runs as long as the value of n is greater than 0. It extracts the last digit of n using the modulo operator %, adds it to the reverse (sum), and then removes the last digit from n by dividing it by 10.
- The reversed number is built digit by digit in the sum variable. For example, if n is 454, then sum becomes 010 + 4 = 4, then 410 + 5 = 45, then 45*10 + 4 = 454, which is the reverse of the original number.
- After the loop completes, the code checks whether the original number (temp) is equal to the reversed number (sum). If they are equal, the number is a palindrome and the program prints "palindrome number". If they are not equal, the number is not a palindrome and the program prints "not palindrome".
- In this specific example, since the original number (454) is the same as its reversed version (454), the program will print "palindrome number".