Introduction
Checking whether a number is a palindrome is one of the most common Java programming exercises and a natural follow-up after learning how to reverse a number. A palindrome number remains exactly the same when its digits are reversed, making this problem an excellent demonstration of how one programming concept can be reused to solve another.
In this guide, you'll learn multiple ways to check whether a number is a palindrome in Java, including the arithmetic approach using a while loop, a recursive solution, and a shortcut using StringBuilder. You'll also understand the difference between palindrome numbers and palindrome strings, explore how Java handles these operations internally, and learn common interview tips and edge cases.
What Is a Palindrome Number?
A palindrome number is a number that reads the same from left to right and right to left.
Examples:
121
1331
12321
7
These numbers remain unchanged after reversing their digits.
Non-palindrome examples:
123
4567
120
Reversing these numbers produces a different value.
Method 1: Using a While Loop (Reverse and Compare)
This is the standard and most commonly used approach.
Java Program
public class PalindromeCheck {
public static void main(String[] args) {
int num = 121;
int original = num;
int reversed = 0;
while (num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num = num / 10;
}
if (original == reversed) {
System.out.println(original + " is a palindrome number.");
} else {
System.out.println(original + " is not a palindrome number.");
}
}
}
Output
121 is a palindrome number.
Step-by-Step Trace (num = 121)
| Iteration | num (before) | digit | reversed | num (after) |
|---|---|---|---|---|
| 1 | 121 | 1 | 1 | 12 |
| 2 | 12 | 2 | 12 | 1 |
| 3 | 1 | 1 | 121 | 0 |
After the loop:
original = 121
reversed = 121
Since both values are equal, the number is a palindrome.
Why Store the Original Number?
The variable num becomes 0 by the end of the reversal process because digits are removed one by one.
Without preserving the original value, there would be nothing meaningful to compare against the reversed number.
Method 2: Using Recursion
The reversal logic can also be implemented recursively.
Java Program
public class PalindromeRecursion {
static int rev = 0;
static void reverse(int num) {
if (num == 0) {
return;
}
rev = rev * 10 + (num % 10);
reverse(num / 10);
}
public static void main(String[] args) {
int num = 12321;
reverse(num);
if (num == rev) {
System.out.println(num + " is a palindrome number.");
} else {
System.out.println(num + " is not a palindrome number.");
}
}
}
Output
12321 is a palindrome number.
How It Works
Each recursive call:
-
Extracts the last digit.
-
Builds the reversed number.
-
Calls itself with the remaining digits.
Once the number becomes zero, recursion stops and the completed reversed number is compared with the original.
Note: Using a shared
staticvariable works for demonstration purposes, but a return-based recursive implementation is generally cleaner and avoids shared state.
Method 3: Using StringBuilder
Java provides a much shorter solution by converting the number into a string.
Java Program
public class PalindromeStringBuilder {
public static void main(String[] args) {
int num = 12321;
String original = String.valueOf(num);
String reversed =
new StringBuilder(original)
.reverse()
.toString();
if (original.equals(reversed)) {
System.out.println(num + " is a palindrome number.");
} else {
System.out.println(num + " is not a palindrome number.");
}
}
}
Output
12321 is a palindrome number.
Why Use .equals() Instead of ==?
Both original and reversed are String objects.
Using:
original == reversed
compares object references rather than the text itself.
Using:
original.equals(reversed)
compares the actual characters, which is what palindrome checking requires.
Palindrome Numbers vs Palindrome Strings
Although similar, these are different problems.
Palindrome Number
Examples:
121
1331
12321
Uses arithmetic operations such as:
-
% -
/
Palindrome String
Examples:
madam
level
racecar
String palindrome problems often require additional preprocessing, such as:
-
converting to lowercase
-
removing spaces
-
ignoring punctuation
For example:
A man a plan a canal Panama
is considered a palindrome after preprocessing.
Number palindrome problems do not require these extra steps.
How Java Handles This Internally
Method 1
The variables:
-
num -
original -
digit -
reversed
are primitive integers stored on the stack.
No heap memory is allocated.
Method 2
Each recursive call creates a new stack frame.
The shared rev variable stores the accumulating reversed number.
Method 3
Objects created on the heap include:
-
String -
StringBuilder
The equals() method compares characters one by one until a mismatch is found or both strings match completely.
Real-Life Analogy
Imagine writing the number:
12321
on a piece of paper.
Now read it from the opposite direction.
1 2 3 2 1
The sequence remains identical.
The same happens with words like:
level
madam
racecar
Anything that looks identical from both directions is a palindrome.
Comparison Table
| Method | Heap Memory | Best Used When |
|---|---|---|
| While Loop | No | Interviews, performance-critical applications |
| Recursion | No (uses call stack) | Learning recursion |
| StringBuilder | Yes | Short, readable solutions |
Best Practices
-
Store the original number before reversing it.
-
Prefer the arithmetic solution in interviews.
-
Use
equals()when comparing strings. -
Extract palindrome logic into a reusable
isPalindrome()method. -
Decide upfront how negative numbers should be handled.
Common Mistakes
Forgetting to Preserve the Original Number
Incorrect:
num = num / 10;
After the loop:
num = 0
Comparing num with the reversed value will always fail.
Using == for String Comparison
Incorrect:
original == reversed
Correct:
original.equals(reversed)
Ignoring Negative Numbers
Numbers like:
-121
need special handling.
Most implementations simply treat negative numbers as not palindromes.
Confusing Number and String Palindromes
Number palindrome logic works only on digits.
String palindrome problems often require removing spaces, punctuation, and converting letters to lowercase.
Assuming Single-Digit Numbers Are Not Palindromes
Every single-digit number is automatically a palindrome.
Examples:
0
5
9
All remain unchanged when reversed.
Expert Tips
-
Mention that palindrome checking builds directly on number reversal.
-
Preserve the original value before modifying the number.
-
Handle edge cases like negative numbers.
-
Use arithmetic for interviews.
-
Mention
StringBuilderas an alternative solution.
Pros and Cons
| Method | Advantages | Disadvantages |
|---|---|---|
| While Loop | Fast, no heap allocation, interview-friendly | Requires reversing the number manually |
| Recursion | Demonstrates recursive thinking | Additional stack usage |
| StringBuilder | Short and easy to understand | Uses heap memory and string conversion |
Frequently Asked Questions
What is a palindrome number?
A palindrome number reads exactly the same forwards and backwards.
Examples:
121
1331
12321
How do I check if a number is a palindrome in Java?
Reverse the digits and compare the reversed value with the original number.
Can I solve this using recursion?
Yes.
Reverse the digits recursively and compare the final reversed number with the original.
Why use .equals() instead of == for strings?
== compares object references.
.equals() compares the actual text.
Are all single-digit numbers palindromes?
Yes.
Every single-digit number remains the same after reversal.
What's the difference between palindrome numbers and palindrome strings?
Number palindromes work on digits.
String palindromes work on characters and may require removing spaces, punctuation, and converting letters to lowercase.
How should negative numbers be handled?
Most implementations consider negative numbers to be not palindrome numbers, since the minus sign has no matching position at the opposite end.
What is the time complexity?
O(d)
where d is the number of digits.
Each digit is processed exactly once.
Can I check a palindrome without reversing the whole number?
Yes.
Another approach compares digits from both ends toward the middle, often using a string or character array.
Is this related to reversing a number?
Yes.
A palindrome check simply reverses the number and compares it with the original.
Is this a common interview question?
Yes.
It is one of the most frequently asked Java programming questions because it combines loops, arithmetic operations, and logical reasoning.
Can this logic work for binary or hexadecimal numbers?
Yes.
Replace base 10 operations (% 10 and / 10) with the desired base, such as % 2 and / 2 for binary.