Blog

Palindrome Program in Java — A Clear Guide (with Examples)

Introduction

A palindrome is a sequence that reads the same forward and backward. Examples: "madam", "racecar", and numeric palindromes like 121 or 1331. Palindromes are a common exercise for beginners learning string handling, loops, and algorithms. In Java, you can check palindromes in several ways: reversing and comparing, two-pointer checking, recursion, or numeric reversal for integers. Below are explanations and practical Java programs you can copy, run, and adapt.

Why learn palindrome checks?

  • Teaches string manipulation and indexing.

  • Introduces two-pointer technique (important for many algorithms).

  • Encourages thinking about edge cases (case, spaces, punctuation, negative numbers).

  • Useful in interview practice and small utilities (e.g., validating symmetric data).

Key approaches (high level)

  1. Reverse and compare — reverse the string and compare with original. Easy and readable.

  2. Two-pointer — compare characters from both ends moving inward; more memory-efficient.

  3. Numeric reverse — for integers, reverse digits and compare (watch overflow and negatives).

  4. Ignoring non-alphanumeric + case-insensitive checks — common in real problems (like palindrome phrases).

Example 1 — Palindrome Program (String) — two methods

Method A: Using StringBuilder.reverse() (simple)

public class PalindromeCheck {
public static boolean isPalindromeUsingReverse(String s) {
if (s == null) return false;
String cleaned = s; // optionally clean: remove spaces/punctuation, and lowercase
String reversed = new StringBuilder(cleaned).reverse().toString();
return cleaned.equals(reversed);
}

public static void main(String[] args) {
String[] tests = {"madam", "Racecar", "step on no pets", "hello"};
for (String t : tests) {
String cleaned = t.replaceAll("[^A-Za-z0-9]", "").toLowerCase();
System.out.printf("\"%s\" -> %b%n", t, isPalindromeUsingReverse(cleaned));
}
}
}

Notes:

  • We cleaned the string to remove non-alphanumeric characters and lowercase it before checking, so "Racecar" and "step on no pets" will be treated as palindromes.

  • This method uses extra memory for the reversed string (O(n) space).

Method B: Two-pointer (no extra string)

public class PalindromeCheck {
public static boolean isPalindromeTwoPointer(String s) {
if (s == null) return false;
int i = 0, j = s.length() - 1;
while (i < j) {
// skip non-alphanumeric if desired
while (i < j && !Character.isLetterOrDigit(s.charAt(i))) i++;
while (i < j && !Character.isLetterOrDigit(s.charAt(j))) j--;
if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))) return false;
i++; j--;
}
return true;
}

public static void main(String[] args) {
String[] tests = {"Madam", "A man, a plan, a canal: Panama", "hello"};
for (String t : tests) {
System.out.printf("\"%s\" -> %b%n", t, isPalindromeTwoPointer(t));
}
}
}

Notes:

  • Two-pointer is O(n) time and O(1) extra space.

  • We skip non-alphanumeric characters and do case-insensitive comparison.

Example 2 — Palindrome Program (Integer)

For integers, you can reverse digits or compare digit-by-digit from ends. Reversing risks overflow for very large integers, so we can reverse only until the halfway point.

public class PalindromeNumber {
public static boolean isPalindrome(int x) {
// Negative numbers are not palindromes (because of the leading '-')
if (x < 0) return false;
// Numbers ending with 0 are not palindromes unless the number is 0
if (x != 0 && x % 10 == 0) return false;

int reverted = 0;
while (x > reverted) {
reverted = reverted * 10 + x % 10;
x /= 10;
}
// For odd length, discard the middle digit by reverted/10
return x == reverted || x == reverted / 10;
}

public static void main(String[] args) {
int[] tests = {121, -121, 10, 12321, 123321};
for (int t : tests) {
System.out.printf("%d -> %b%n", t, isPalindrome(t));
}
}
}

Why this works: The loop builds the reversed lower half of the number. When the original x becomes less than or equal to reverted, we have processed half (or half+1) of the digits. This avoids overflow and is O(log10(n)) time.

Complexity summary

  • String reverse & compare: Time O(n), Space O(n) (due to reversed string).

  • Two-pointer string: Time O(n), Space O(1) (ignoring input).

  • Integer half-reverse: Time O(d) where d = number of digits (≈O(log n)), Space O(1).

Common pitfalls & tips

  • Case sensitivity: Convert to lower/upper case if you want case-insensitive checks.

  • Spaces and punctuation: Use replaceAll("[^A-Za-z0-9]", "") or two-pointer skipping to ignore non-alphanumerics.

  • Negative numbers: Conventionally not palindromes because of - sign.

  • Leading zeros: 010 as string can be palindrome, but as integer 10 is not.

  • Integer overflow: Don’t fully reverse huge integers into another int—use the half-reverse trick or use long with care.

  • Unicode: If handling non-ASCII text, consider using int code points rather than char and be careful with normalization.

Testing suggestions

Try these tests:

  • Simple: "madam", "hello".

  • Case: "RaceCar".

  • Phrases: "A man, a plan, a canal: Panama".

  • Numbers: 121, -121, 10, 12321.

  • Edge cases: empty string "" (decide whether to treat as palindrome), single-character strings, very long strings.

Conclusion

A palindrome program in Java is an excellent exercise for learning string handling and algorithmic thinking. For most purposes, the two-pointer string method is efficient and simple; for integers, the half-reverse technique is safe and avoids overflow. Start with the straightforward StringBuilder.reverse() approach to understand the idea, then move to two-pointer or numeric half-reverse for better space efficiency and interview-style solutions.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button