Program to Check if a Number is a Palindrome in Java
Palindrome Number
A palindrome number is a number that remains the same when its digits are reversed. For example, 121 and 1331 are palindrome numbers.
We will explore a method to check if a number is a palindrome using Java programming.
Method: Using a while Loop
We reverse the number and compare it with the original number.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int originalNum = num, reversed = 0, digit;
// Loop to extract and reverse digits
while (num > 0) {
digit = num % 10; // Extract last digit
reversed = reversed * 10 + digit; // Construct reversed number
num /= 10; // Remove last digit from number
}
// Check if original and reversed numbers are the same
if (originalNum == reversed)
System.out.println(originalNum + " is a palindrome number");
else
System.out.println(originalNum + " is not a palindrome number");
scanner.close();
}
}
Output:
Enter a number: 121 121 is a palindrome number