Check Palindrome Number in Java
What you’ll learn
- What a palindrome number means (same forward and backward).
- How to reverse digits using
% 10and/ 10in Java. - How to check one number and print palindromes in a range.
Overview
A number is palindrome when its digits read the same from both ends. We reverse digits using arithmetic and compare with the original value.
Prerequisites
Integer arithmetic, modulo/division by 10, and loops.
- Use
% 10to get the last digit and/ 10to remove it. - Basic Java control flow with
whileloops and comparisons.
Core idea
Reverse the digits and compare the reversed value with the original number.
Live preview
Algorithm
Build reversed from last digits and test original == reversed.
📜 Pseudocode
original = n
reversed = 0
while n != 0:
reversed = reversed * 10 + (n % 10)
n = n / 10
return original == reversedCheck one number
public class Main {
static boolean isPalindrome(int number) {
int original = number;
int reversed = 0;
while (number != 0) {
int digit = number % 10;
reversed = reversed * 10 + digit;
number /= 10;
}
return original == reversed;
}
public static void main(String[] args) {
int number = 121;
if (isPalindrome(number)) {
System.out.println(number + " is a palindrome number.");
} else {
System.out.println(number + " is not a palindrome number.");
}
}
}Palindromes from 100 to 200
public class Main {
static boolean isPalindrome(int number) {
int original = number;
int reversed = 0;
while (number != 0) {
int digit = number % 10;
reversed = reversed * 10 + digit;
number /= 10;
}
return original == reversed;
}
public static void main(String[] args) {
System.out.println("Palindrome numbers in the range 100 to 200:");
for (int i = 100; i <= 200; i++) {
if (isPalindrome(i)) {
System.out.print(i + " ");
}
}
System.out.println();
}
}Optimization
For simple interviews, full reverse is enough. Advanced variant compares half-digits to reduce overflow risk.
❓ FAQ
🔄 Input / output examples
121 -> palindrome, 123 -> not palindrome, 0 -> palindrome.
Edge cases
Negative values are treated as non-palindromes in this tutorial scope; watch integer overflow if reversing very large numbers.
⏱️ Time and space complexity
Single check: O(d) where d is number of digits, extra space O(1).
Summary
- Reverse digits and compare to original.
- Complexity is linear in digit count.
Single-digit numbers like 7 are always palindrome numbers because they read the same in both directions.
8 people found this page helpful
