Check if a String is a Palindrome in Java

1. Introduction

In this article, we’re going to see how we can check whether a given String is a palindrome using Java.

A palindrome is a word, phrase, number, or other sequences of characters which reads the same backward as forward, such as “madam” or “racecar”.

2. Solutions

In the following sections, we’ll look at the various ways of checking if a given String is a palindrome or not.

2.1. A Simple Approach

We can simultaneously start iterating the given string forward and backward, one character at a time. If the there is a match the loop continues; otherwise, the loop exits:

public boolean isPalindrome(String text) {
    String clean = text.replaceAll("\\s+", "").toLowerCase();
    int length = clean.length();
    int forward = 0;
    int backward = length - 1;
    while (backward > forward) {
        char forwardChar = clean.charAt(forward++);
        char backwardChar = clean.charAt(backward--);
        if (forwardChar != backwardChar)
            return false;
    }
    return true;
}

2.2. Reversing the String

There are a few different implementations that fit this use case: we can make use of the API methods from StringBuilder and StringBuffer classes when checking for palindromes, or we can reverse the String without these classes.

Let’s take a look at the code implementations without the helper APIs first:

public boolean isPalindromeReverseTheString(String text) {
    StringBuilder reverse = new StringBuilder();
    String clean = text.replaceAll("\\s+", "").toLowerCase();
    char[] plain = clean.toCharArray();
    for (int i = plain.length - 1; i >= 0; i--) {
        reverse.append(plain[i]);
    }
    return (reverse.toString()).equals(clean);
}

In the above snippet, we simply iterate the given String from the last character and append each character to the next character, all the way through to the first character thereby reversing the given String.

Finally, we test for equality between the given String and reversed String.

The same behavior could be achieved using API methods.

Let’s see a quick demonstration:

public boolean isPalindromeUsingStringBuilder(String text) {
    String clean = text.replaceAll("\\s+", "").toLowerCase();
    StringBuilder plain = new StringBuilder(clean);
    StringBuilder reverse = plain.reverse();
    return (reverse.toString()).equals(clean);
}

public boolean isPalindromeUsingStringBuffer(String text) {
    String clean = text.replaceAll("\\s+", "").toLowerCase();
    StringBuffer plain = new StringBuffer(clean);
    StringBuffer reverse = plain.reverse();
    return (reverse.toString()).equals(clean);
}

In the code snippet, we invoke the reverse() method from the StringBuilder and StringBuffer API to reverse the given String and test for equality.

2.3. Using Stream API

We can also use an IntStream to provide a solution:

public boolean isPalindromeUsingIntStream(String text) {
    String temp  = text.replaceAll("\\s+", "").toLowerCase();
    return IntStream.range(0, temp.length() / 2)
      .noneMatch(i -> temp.charAt(i) != temp.charAt(temp.length() - i - 1));
}

In the snippet above, we verify that none of the pairs of characters from each end of the String fulfills the Predicate condition.

2.4. Using Recursion

Recursion is a very popular method to solve these kinds of problems. In the example demonstrated we recursively iterate the given String and test to find out whether it’s a palindrome or not:

public boolean isPalindromeRecursive(String text){
    String clean = text.replaceAll("\\s+", "").toLowerCase();
    return recursivePalindrome(clean,0,clean.length()-1);
}

private boolean recursivePalindrome(String text, int forward, int backward) {
    if (forward == backward) {
        return true;
    }
    if ((text.charAt(forward)) != (text.charAt(backward))) {
        return false;
    }
    if (forward < backward + 1) {
        return recursivePalindrome(text, forward + 1, backward - 1);
    }

    return true;
}

3. Conclusion

In this quick tutorial, we saw how to find out whether a given String is a palindrome or not.

As always, the code examples for this article are available over on GitHub.

Related posts:

Java 8 Streams peek() API
Multipart Upload with HttpClient 4
Introduction to Spring Cloud Rest Client with Netflix Ribbon
Java – InputStream to Reader
Converting Strings to Enums in Java
Spring REST API + OAuth2 + Angular (using the Spring Security OAuth legacy stack)
Java Program to Solve any Linear Equations
Mix plain text and HTML content in a mail
Guide to Escaping Characters in Java RegExps
Java Program to Check whether Undirected Graph is Connected using DFS
Java Program to Implement Find all Back Edges in a Graph
Java Program to Find the Longest Path in a DAG
Hướng dẫn Java Design Pattern – Proxy
Spring Webflux and CORS
The DAO with JPA and Spring
Spring Boot - Scheduling
Tìm hiểu cơ chế Lazy Evaluation của Stream trong Java 8
Java Program to Perform Postorder Recursive Traversal of a Given Binary Tree
Get and Post Lists of Objects with RestTemplate
Toán tử instanceof trong java
Java Program to Find Nearest Neighbor for Dynamic Data Set
Hướng dẫn sử dụng Java Generics
Java Program to Solve the 0-1 Knapsack Problem
Working with Network Interfaces in Java
Java Program to Check the Connectivity of Graph Using DFS
Java Program to Implement Find all Forward Edges in a Graph
Java Program to Find ith Largest Number from a Given List Using Order-Statistic Algorithm
Using Spring @ResponseStatus to Set HTTP Status Code
Java Program to Implement K Way Merge Algorithm
Spring Boot Change Context Path
Java Program to Perform Inorder Non-Recursive Traversal of a Given Binary Tree
Spring Security 5 for Reactive Applications