Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to check if a string is a palindrome

Short answer

A palindrome reads the same left to right and right to left. Compare the string with its reversed copy:

void main() {
    String word = "level";
    boolean palindrome = word.equals(new StringBuilder(word).reverse().toString());
 
    IO.println(palindrome);
}

Output:

true

Two pointers

Without an extra string: compare characters from both ends and move towards the middle:

boolean isPalindrome(String text) {
    int left = 0;
    int right = text.length() - 1;
    while (left < right) {
        if (text.charAt(left) != text.charAt(right)) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}
 
void main() {
    IO.println(isPalindrome("racecar"));
    IO.println(isPalindrome("java"));
}

Output:

true
false

A phrase

For phrases, remove everything except letters and digits and bring the text to one case:

void main() {
    String phrase = "A man, a plan, a canal: Panama";
    String clean = phrase.replaceAll("[^\\p{L}\\p{N}]", "").toLowerCase();
 
    IO.println(clean);
    IO.println(clean.equals(new StringBuilder(clean).reverse().toString()));
}

Output:

amanaplanacanalpanama
true

Common mistake

Comparing the strings with ==. The reversed string is a new object, so the result is always false:

void main() {
    String word = "level";
    String reversed = new StringBuilder(word).reverse().toString();
 
    IO.println(word == reversed);
    IO.println(word.equals(reversed));
}

Output:

false
true

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.