A palindrome number is a number that remains the same even when the order of its digits is reversed. For example, 121, 12321, 1001, etc., are all examples of palindrome numbers. In this article, we will explore how to check if a number is a palindrome using a Java program.
To determine whether a number is a palindrome, we will compare the original number with its reversed version. If both are equal, then the number is a palindrome, otherwise not.
The steps we will use are as follows:
- Store the number to be checked in a variable.
- Reverse the number.
- Compare the original number with the reversed number.
- If both are the same, it’s a palindrome. If not, it’s not a palindrome.
Now, let’s translate these steps into Java code.
Below is a simple Java program that checks if a number is a palindrome.
- Import Scanner class: We import the Scanner class from the java.util package to read the number from the user.
- Read the number: We create a Scanner object and use its nextInt() method to read the number from the user.
- Calculate the reverse of the number: We initialize reverse to 0 and then enter a loop that continues as long as num is not 0. Inside the loop, we first calculate the remainder of num divided by 10. This gives us the last digit of num. We then multiply reverse by 10 and add the remainder to it. This effectively appends the last digit of num to reverse. Finally, we divide num by 10 to remove its last digit.
- Check if the number is a palindrome: After the loop, reverse holds the reverse of the original number. We then check if originalNum and reverse are equal. If they are, we print a message saying that the number is a palindrome. Otherwise, we print a message saying it’s not.
A palindrome number is a number that maintains its identity even when the order of its digits is reversed. We can use a simple Java program to check whether a given number is a palindrome. The key part of the program is a loop that calculates the reverse of the number. After the loop, we compare the original number with its reverse to determine if it’s a palindrome. This exercise provides a good demonstration of several fundamental programming concepts, including loops, if statements, and basic I/O.