Java Program to Check Palindrome String

Palindrome strings are a popular concept in computer science and coding interviews. 

A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). 

In this blog post, we'll see the two easiest ways to write a program step-by-step to check if a given string is a palindrome in Java.

Java Program to Check Palindrome String using Loop 

Program Explanation 

Let's break down the process: 

Remove Unwanted Characters and Normalize: Since we want to ignore spaces, punctuation, and capitalization, start by cleaning up the string. 

Two Pointers Approach: Use two pointers, one at the beginning and the other at the end of the string. Move them towards each other while comparing the characters they point to. 

Java Program

Here's the Java code to determine if a string is a palindrome:

public class PalindromeChecker {

    public static boolean isPalindrome(String str) {
        // Step 1: Normalize the string
        String cleaned = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
        
        int left = 0;
        int right = cleaned.length() - 1;

        // Step 2: Two Pointers Approach
        while (left < right) {
            if (cleaned.charAt(left) != cleaned.charAt(right)) {
                return false;  // It's not a palindrome if there's a mismatch
            }
            left++;
            right--;
        }
        return true;
    }

    public static void main(String[] args) {
        String testString = "A man, a plan, a canal, Panama";
        boolean result = isPalindrome(testString);
        System.out.println("Is the string \"" + testString + "\" a palindrome? " + result);
    }
}

Output:

Is the string "A man, a plan, a canal, Panama" a palindrome? true

String cleaned = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase(): This line removes any character that isn't a letter or number and converts the string to lowercase. It prepares the string for palindrome checking by normalizing it. 

The two-pointer approach is a common technique to solve such problems. We compare characters from the start and end of the string and move the pointers inward. If the characters don't match, we can conclude it's not a palindrome.

Java Program to Check Palindrome String using StringBuilder

This is the most straightforward method to check for a palindrome is to reverse the string and then compare the original string with the reversed one.

The Strategy 

To determine if a string is a palindrome: 

  • Convert the string to a uniform case (either all lowercase or all uppercase). 
  • Reverse the string. 
  • Compare the original string with the reversed string. If they're the same, it's a palindrome! 

The Java Program

Here's the Java code to determine if a string is a palindrome:

public class PalindromeChecker {

    public static void main(String[] args) {
        String input = "Radar";
        if (isPalindrome(input)) {
            System.out.println("\"" + input + "\" is a palindrome!");
        } else {
            System.out.println("\"" + input + "\" is not a palindrome.");
        }
    }

    public static boolean isPalindrome(String str) {
        // Step 1: Convert the string to lowercase
        String cleanString = str.toLowerCase();

        // Step 2: Reverse the string
        String reversed = new StringBuilder(cleanString).reverse().toString();

        // Step 3: Compare the original string with the reversed string
        return cleanString.equals(reversed);
    }
}

Output:

"Radar" is a palindrome!

Explaining the Program 

Convert to a Uniform Case:

String cleanString = str.toLowerCase();

We convert the entire string to lowercase using the toLowerCase() method. This ensures that our comparison is case-insensitive. So, "Radar" and "radar" would both be recognized as palindromes.

Reverse the String:

String reversed = new StringBuilder(cleanString).reverse().toString();

We use Java's StringBuilder class which offers a handy reverse() method. After reversing, we convert the StringBuilder back to a string. 

Compare the Original and Reversed Strings:

return cleanString.equals(reversed);

We use the equals() method to check if the original string matches the reversed string. If they match, it means the string is a palindrome, and the method will return true; otherwise, it will return false.

Conclusion

Checking if a string is a palindrome is a classic problem, and as we've seen, there are multiple ways to solve it in Java. While the StringBuilder method is concise, the loop method gives more control and is generally faster for longer strings. Choose the method that best fits your needs, but also understand the mechanics behind each!

Related Java String Programs with Output

Comments