Palindrome Program in Java: How to Check a Palindrome With Examples
Learn how to build a palindrome program in Java for numbers and strings using loops, StringBuilder, two pointers, and recursion.
Table of Contents ▼
- Quick Answer
- What Is a Palindrome in Java?
- How the Palindrome Algorithm Works
- Palindrome Program in Java Using a While Loop
- Check a String With StringBuilder
- String Palindrome Without the Reverse Method
- Palindrome Checking With Recursion
- Which Java Palindrome Method Should You Use?
- Edge Cases and Common Mistakes
- Frequently Asked Questions
- Can a palindrome program accept both numbers and strings?
- How do I check a palindrome in Java without a built-in function?
- Is zero a palindrome number?
- Why should the original number be stored in another variable?
- Is StringBuilder or the two-pointer method better?
- What is the time complexity of checking a palindrome?
- Choosing a Clear and Reliable Solution
A palindrome program in Java checks whether a number or piece of text reads the same from left to right and right to left. For example, 121, level, and madam are palindromes, while 123 and hello are not. The basic idea is to reverse the input and compare it with the original, or compare matching values from both ends.
The best implementation depends on the input and what you want to practice. Arithmetic is useful for numbers, StringBuilder provides a short string solution, two pointers avoid creating a reversed copy, and recursion demonstrates how a method can solve smaller versions of the same problem. The examples below are complete Java programs with user input, output, explanations, complexity, and practical edge cases.
Quick Answer
To check a palindrome in Java, save the original input, reverse it, and compare both values. For an integer, build the reverse one digit at a time with % 10 and / 10. For text, use StringBuilder.reverse() or compare characters at matching positions with two pointers. Equal values mean the input is a palindrome.
What Is a Palindrome in Java?
A palindrome is a sequence that remains unchanged when its order is reversed. It may be a number, word, or phrase. Common examples include:
- 7, because every single digit reads the same both ways
- 1221, because its reversed number is also 1221
- racecar, because the first and last characters match as the comparison moves inward
- Never odd or even, if spaces and letter case are ignored
The definition depends on the rules chosen by the program. A strict string comparison treats uppercase letters, spaces, and punctuation as meaningful. A normalized comparison can ignore those differences. Numeric programs also need a rule for negative values. In most programming problems, -121 is not a palindrome because the minus sign appears only at the front.
How the Palindrome Algorithm Works
For an integer, the algorithm stores the original number and creates a reversed number. Suppose the input is 12321:
% 10extracts the final digit. For example,12321 % 10returns1.- The program appends that digit with
reversedNumber * 10 + digit. / 10removes the final digit through integer division. Here,12321 / 10becomes1232.- The loop continues until no digits remain.
- The original and reversed values are compared.
Saving the original value is necessary because the loop repeatedly shortens its working copy. Without a separate originalNumber, the program would finish with 0 and compare the wrong values.
For a string palindrome, the program can reverse the entire string or compare the first character with the last, the second with the second-last, and so on.

Figure 1: Integer palindrome checking extracts digits using arithmetic modulo and integer division.
Palindrome Program in Java Using a While Loop
This example reads an integer with Scanner. It uses a long for the reversed value so reversing a valid int does not overflow another int.
import java.util.Scanner;
public class PalindromeNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
int originalNumber = number;
int workingNumber = number;
long reversedNumber = 0;
if (number >= 0) {
while (workingNumber != 0) {
int digit = workingNumber % 10;
reversedNumber = reversedNumber * 10 + digit;
workingNumber = workingNumber / 10;
}
}
if (number >= 0 && originalNumber == reversedNumber) {
System.out.println(
originalNumber + " is a palindrome number.");
} else {
System.out.println(
originalNumber + " is not a palindrome number.");
}
scanner.close();
}
}
Sample input and output:
Enter an integer: 12321
12321 is a palindrome number.
This palindrome program in Java also handles zero correctly. The loop does not run for 0, but both the original and reversed values are zero. Negative inputs go directly to the non-palindrome result. If the application needs integers larger than the int range, read a long and add a suitable overflow check, or accept the value as a string.
The method processes each digit once, so its time complexity is O(d), where d is the number of digits. It uses O(1) auxiliary space.
Check a String With StringBuilder
StringBuilder.reverse() offers a clear solution when creating a reversed copy is acceptable. The program below removes punctuation and spaces, converts letters to lowercase, and then compares the normalized and reversed strings.
import java.util.Locale;
import java.util.Scanner;
public class StringBuilderPalindrome {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter text: ");
String input = scanner.nextLine();
String normalized = input
.replaceAll("[^A-Za-z0-9]", "")
.toLowerCase(Locale.ROOT);
String reversed =
new StringBuilder(normalized).reverse().toString();
if (normalized.equals(reversed)) {
System.out.println("The text is a palindrome.");
} else {
System.out.println("The text is not a palindrome.");
}
scanner.close();
}
}
Sample input and output:
Enter text: Never odd or even!
The text is a palindrome.
Use equals() rather than == for string comparison. equals() compares character content, while == checks whether two references point to the same object. Reversing and comparing both take O(n) time. The normalized and reversed strings require O(n) additional space.

Figure 2: Two-pointer inspection verifies symmetry by comparing characters inward from both ends.
String Palindrome Without the Reverse Method
A two-pointer approach compares characters in place. One pointer starts on the left and another on the right. Each pointer skips punctuation, then the characters are compared without case sensitivity. The method stops immediately when it finds a mismatch.
import java.util.Scanner;
public class TwoPointerPalindrome {
static boolean isPalindrome(String text) {
int left = 0;
int right = text.length() - 1;
while (left < right) {
while (left < right &&
!Character.isLetterOrDigit(
text.charAt(left))) {
left++;
}
while (left < right &&
!Character.isLetterOrDigit(
text.charAt(right))) {
right--;
}
char leftChar =
Character.toLowerCase(text.charAt(left));
char rightChar =
Character.toLowerCase(text.charAt(right));
if (leftChar != rightChar) {
return false;
}
left++;
right--;
}
return true;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter text: ");
String input = scanner.nextLine();
System.out.println(isPalindrome(input)
? "The text is a palindrome."
: "The text is not a palindrome.");
scanner.close();
}
}
Sample input and output:
Enter text: A man, a plan, a canal: Panama!
The text is a palindrome.
Each character is inspected at most once, giving O(n) time. Because the method does not build a normalized or reversed copy, it uses O(1) auxiliary space. This makes two pointers a strong choice for long strings and coding interviews.
Palindrome Checking With Recursion
Recursion checks the two outer characters and then calls the same method for the smaller inner range. The base case occurs when the pointers meet or cross.
import java.util.Locale;
import java.util.Scanner;
public class RecursivePalindrome {
static boolean isPalindrome(
String text, int left, int right) {
if (left >= right) {
return true;
}
if (text.charAt(left) != text.charAt(right)) {
return false;
}
return isPalindrome(text, left + 1, right - 1);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter text: ");
String input = scanner.nextLine();
String normalized = input
.replaceAll("[^A-Za-z0-9]", "")
.toLowerCase(Locale.ROOT);
boolean result = isPalindrome(
normalized, 0, normalized.length() - 1);
System.out.println(result
? "The text is a palindrome."
: "The text is not a palindrome.");
scanner.close();
}
}
Sample input and output:
Enter text: Level
The text is a palindrome.
The recursive comparisons take O(n) time. The call stack uses O(n) space in Big-O terms, even though only about half of the characters create calls. Normalization also creates an O(n) string. Recursion is helpful for learning, but an iterative two-pointer method is safer for very long input because it does not risk exhausting the call stack.

Figure 3: Recursion peels away matching outer elements to verify inner subproblems down to base cases.
Which Java Palindrome Method Should You Use?
| Method | Best Use | Time Complexity | Auxiliary Space |
|---|---|---|---|
| Arithmetic reversal | Integer input and digit practice | O(d) | O(1) |
| StringBuilder.reverse() | Short, readable string code | O(n) | O(n) |
| Two pointers | Efficient production string checking | O(n) | O(1) |
| Recursion | Learning recursive logic & base cases | O(n) | O(n) |
For a beginner number exercise, use the while-loop version. For production-style text checking, two pointers provide good control over case, punctuation, and memory. Use StringBuilder when clarity matters more than minimizing extra space.
Edge Cases and Common Mistakes
- Zero and single digits: They are palindromes because reversing them produces the same value.
- Negative numbers: Most definitions treat them as non-palindromes because of the minus sign.
- Case and punctuation: Decide whether
Leveland phrases with spaces should be normalized before comparison. - Empty input: The sample string methods treat an empty or punctuation-only sequence as a palindrome. Add a validation rule if your application should reject it.
- Integer overflow: A reversed integer may exceed its data type. A wider type (
long) helps forintinput, while strings are safer for extremely large numbers. - Modified original value: Do not destroy the only copy of a number before the final comparison.
- Using
==for strings: Compare string content withequals()or compare individual characters.
Frequently Asked Questions
Can a palindrome program accept both numbers and strings?
Yes. Reading the input as a String provides one flexible solution because digits are characters too. You can normalize the text and compare both ends. However, an arithmetic solution is better when the exercise specifically tests modulo, integer division, and number reversal.
How do I check a palindrome in Java without a built-in function?
Use two indices named left and right. Compare the characters at those positions, then move both indices toward the center. Return false when a pair differs. If the indices meet or cross without a mismatch, return true. This takes O(n) time and O(1) auxiliary space.
Is zero a palindrome number?
Yes. Reversing 0 still produces 0, so it meets the definition. A number-reversal loop may execute zero times for this input, but the final comparison between the original value and the initialized reversed value still returns a match.
Why should the original number be stored in another variable?
The reversal loop removes digits from its working number using integer division. By the time the loop finishes, that value is usually zero. A separate variable preserves the initial input so the program can compare it with the completed reversed number.
Is StringBuilder or the two-pointer method better?
StringBuilder is shorter and easy to understand, but it creates a reversed copy. Two pointers compare the existing string and can use constant auxiliary space. For beginner exercises, either is suitable. For large inputs or interview discussions about memory, two pointers are usually the stronger answer.
What is the time complexity of checking a palindrome?
The standard methods take O(n) time because they inspect each digit or character no more than a constant number of times. Arithmetic reversal and direct two-pointer comparison use O(1) auxiliary space. Building new strings or using recursion requires O(n) additional space.
Choosing a Clear and Reliable Solution
A good palindrome program in Java starts with a clear rule for the input. Use arithmetic for integers, StringBuilder for a concise string solution, two pointers for efficient character comparison, or recursion when practicing method calls and base cases. Whatever approach you choose, preserve the original value, handle normalization deliberately, and test edge cases before relying on the result.
Check Your Own Words & Numbers
Test any word, sentence, date, or number with our interactive palindrome tool. Automatically normalizes punctuation, spaces, and casing.
Related Articles
Explore more in-depth guides and analysis.
Palindrome Python Guide: Check Strings and Numbers
Learn palindrome Python methods for strings and numbers using slicing, loops, functions, recursion, text normalization, and practical examples for beginners.
What Is a Palindrome? Meaning, Types, and Examples
What is a palindrome? Learn its meaning, pronunciation, types, and clear examples using words, phrases, names, numbers, dates, and times in simple language.
Numbers That Are Palindromes: Examples, Patterns, and Facts
Learn which numbers are palindromes, see clear examples and digit patterns, count them by length, and understand primes, squares, zero, and key rules.