What is a Palindrome Number?
A palindrome number is one that remains the same when its digits are reversed. For example, "121" and "1001" are palindromes because they read the same backward and forward. In contrast, "723" and "327" are not palindromes.
The Java Program
Let's dive into the Java program that checks if a number is a palindrome:
package in.studyecart.impprograms;
import java.util.Scanner;
public class SECJAP112 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please Enter a Number for Checking Palindrome or Not:");
int actual_num = input.nextInt(), reverse_num = 0, current_num = actual_num;
while (actual_num != 0) {
int digit = actual_num % 10;
reverse_num = (reverse_num * 10) + digit;
actual_num = actual_num / 10;
}
if (current_num == reverse_num) {
System.out.println(current_num + " is Palindrome!!");
} else {
System.out.println(current_num + " is Not Palindrome!!");
}
}
}
(code-box)
How Does the Program Work?
1. We start by defining a Scanner to take user input for the number to be checked.
2. We use a `while` loop to reverse the digits of the number. It calculates the reverse by repeatedly extracting the last digit and adding it to the `reverse_num`.
3. After reversing, we compare the original number (`current_num`) with the reversed number (`reverse_num`) to determine if it's a palindrome or not.
That's it! With this Java program, you can easily check if a number is a palindrome. Remember, palindromes are fun, but understanding the code behind them is even more satisfying. So, go ahead, give it a try, and have fun experimenting with different numbers!
Ready to explore more Java programming concepts? Stay tuned for more exciting tutorials and coding adventures!
Top 10 Java Programs for Beginners - click here
Understanding Armstrong Numbers in Java - Explained with Code - Click here
Understanding Armstrong Numbers in Java - Explained with Code - Click here