5 Ways to Check if a String Is a Palindrome in Java

admin5 min read
In this tutorial
  1. 1. Reverse with StringBuilder
  2. 2. Two pointers
  3. 3. Recursion
  4. 4. Streams
  5. 5. Real-world version: ignore case, spaces and punctuation
  6. Putting it all together
  7. Which one should you use?
  8. Practice extensions

“Write a method that checks whether a string is a palindrome” is one of the most common coding questions in Java interviews and university assignments. A palindrome reads the same forwards and backwards: “level”, “racecar”, “madam”.

The problem is simple, which is exactly why interviewers like it: they want to see how you think about edge cases, efficiency and clean code. Here are five solutions, from the quickest to write to the most robust.

1. Reverse with StringBuilder

The shortest solution: reverse the string and compare.

static boolean isPalindromeReverse(String s) {
    return new StringBuilder(s).reverse().toString().equals(s);
}
  • Time: O(n). Extra space: O(n) for the reversed copy.
  • Very readable, and perfectly fine in real code. In an interview, expect a follow-up: “Can you do it without creating a new string?”

2. Two pointers

Compare characters from both ends, moving towards the middle. Stop as soon as you find a mismatch.

static boolean isPalindromeTwoPointers(String s) {
    int left = 0;
    int right = s.length() - 1;
    while (left < right) {
        if (s.charAt(left) != s.charAt(right)) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}
  • Time: O(n), and often faster in practice because it can stop early.
  • Extra space: O(1).

This is the answer most interviewers are hoping for. The two-pointer technique also solves many other problems, such as reversing an array in place or finding pairs that sum to a target in a sorted array.

Tracing “racecar”

  • Compare r and r: match. Move inwards.
  • Compare a and a: match.
  • Compare c and c: match.
  • left (3) is no longer less than right (3), so stop: it is a palindrome.

3. Recursion

A string is a palindrome if its first and last characters match and the part in between is a palindrome.

static boolean isPalindromeRecursive(String s, int left, int right) {
    if (left >= right) {
        return true;                 // base case: 0 or 1 characters left
    }
    if (s.charAt(left) != s.charAt(right)) {
        return false;
    }
    return isPalindromeRecursive(s, left + 1, right - 1);
}
  • Time: O(n). Space: O(n) on the call stack.
  • Elegant and a good way to show you understand recursion, but a very long string could cause a StackOverflowError. Avoid s.substring(1, s.length() - 1) in each call: it copies the string every time and makes the solution O(n²).

4. Streams

A functional one-liner using IntStream:

import java.util.stream.IntStream;

static boolean isPalindromeStream(String s) {
    int n = s.length();
    return IntStream.range(0, n / 2)
            .allMatch(i -> s.charAt(i) == s.charAt(n - 1 - i));
}

allMatch stops at the first mismatch, so this is O(n) time and O(1) extra space, like the two-pointer version. It shows you know the Stream API, though many developers find the loop easier to read.

5. Real-world version: ignore case, spaces and punctuation

Phrases like “A man, a plan, a canal: Panama” are palindromes if you only look at letters and digits, ignoring case. This is also LeetCode problem 125, “Valid Palindrome”.

static boolean isPalindromePhrase(String s) {
    int left = 0;
    int right = s.length() - 1;
    while (left < right) {
        char a = s.charAt(left);
        char b = s.charAt(right);
        if (!Character.isLetterOrDigit(a)) {
            left++;
        } else if (!Character.isLetterOrDigit(b)) {
            right--;
        } else {
            if (Character.toLowerCase(a) != Character.toLowerCase(b)) {
                return false;
            }
            left++;
            right--;
        }
    }
    return true;
}

This skips non-alphanumeric characters without building a cleaned copy, so it stays O(n) time and O(1) space.

An easier-to-read alternative, at the cost of O(n) extra space:

String cleaned = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();
return isPalindromeTwoPointers(cleaned);

Putting it all together

import java.util.stream.IntStream;

public class Palindromes {
    // ... the five methods above ...

    public static void main(String[] args) {
        String[] tests = {"racecar", "level", "kooredev", "", "a", "Noon"};
        for (String t : tests) {
            System.out.printf("%-10s reverse=%-5b twoPointers=%-5b recursive=%-5b stream=%b%n",
                    "\"" + t + "\"",
                    isPalindromeReverse(t),
                    isPalindromeTwoPointers(t),
                    isPalindromeRecursive(t, 0, t.length() - 1),
                    isPalindromeStream(t));
        }
        System.out.println(isPalindromePhrase("A man, a plan, a canal: Panama")); // true
        System.out.println(isPalindromePhrase("Kooredev rocks"));                 // false
    }
}

Output:

"racecar"  reverse=true  twoPointers=true  recursive=true  stream=true
"level"    reverse=true  twoPointers=true  recursive=true  stream=true
"kooredev" reverse=false twoPointers=false recursive=false stream=false
""         reverse=true  twoPointers=true  recursive=true  stream=true
"a"        reverse=true  twoPointers=true  recursive=true  stream=true
"Noon"     reverse=false twoPointers=false recursive=false stream=false

Notice the edge cases: an empty string and a single character count as palindromes, and “Noon” is not a palindrome when case matters. Ask your interviewer how they want case and spaces handled. Asking clarifying questions is part of a good answer.

Which one should you use?

  • In application code: the StringBuilder version for plain strings, or version 5 for user-entered phrases. Readability wins.
  • In an interview: start by mentioning the reverse approach, then write the two-pointer solution and explain why it uses O(1) space.
  • Avoid the recursive substring version for long inputs.

Practice extensions

  1. Check whether an integer is a palindrome without converting it to a string (hint: reverse the digits with % 10 and / 10).
  2. Find the longest palindromic substring in a string.
  3. Check whether any permutation of a string could form a palindrome (hint: count characters with a HashMap, and at most one count can be odd).

More practice: Core Java interview questions for freshers.

Ask a question or leave a comment

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