Java Program to Check if Input String is Palindrome

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

Introduction

A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). Checking if a string is a palindrome is a common task in text processing. In this blog post, we will explore various methods to check if an input string is a palindrome in Java.

Table of Contents

  1. Using a Simple Loop
  2. Using StringBuilder's reverse() Method
  3. Using Java 8 Streams
  4. Complete Example Program
  5. Conclusion

1. Using a Simple Loop

One of the simplest methods to check if a string is a palindrome is by comparing characters from the start and end of the string moving towards the center.

Example:

public class PalindromeCheckUsingLoop {
    public static void main(String[] args) {
        String input = "Madam";
        boolean result = isPalindrome(input);
        System.out.println("Is the string \"" + input + "\" a palindrome? " + result);
    }

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

        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}

Output:

Is the string "Madam" a palindrome? true

Explanation:

  • The string is converted to lowercase and all non-alphanumeric characters are removed to normalize the input.
  • A loop is used to compare characters from the start and end of the string moving towards the center.
  • If any characters do not match, the string is not a palindrome.

2. Using StringBuilder's reverse()() Method

Another method to check if a string is a palindrome is by reversing the string and comparing it to the original string.

Example:

public class PalindromeCheckUsingStringBuilder {
    public static void main(String[] args) {
        String input = "Madam";
        boolean result = isPalindrome(input);
        System.out.println("Is the string \"" + input + "\" a palindrome? " + result);
    }

    public static boolean isPalindrome(String str) {
        str = str.toLowerCase().replaceAll("[^a-zA-Z0-9]", ""); // Normalizing the input
        String reversedStr = new StringBuilder(str).reverse().toString();
        return str.equals(reversedStr);
    }
}

Output:

Is the string "Madam" a palindrome? true

Explanation:

  • The string is normalized by converting it to lowercase and removing non-alphanumeric characters.
  • The StringBuilder's reverse() method is used to reverse the string.
  • The reversed string is compared to the original string to determine if it is a palindrome.

3. Using Java 8 Streams

Java 8 Streams provide a modern and concise way to check if a string is a palindrome.

Example:

import java.util.stream.IntStream;

public class PalindromeCheckUsingStreams {
    public static void main(String[] args) {
        String input = "Madam";
        boolean result = isPalindrome(input);
        System.out.println("Is the string \"" + input + "\" a palindrome? " + result);
    }

    public static boolean isPalindrome(String str) {
        str = str.toLowerCase().replaceAll("[^a-zA-Z0-9]", ""); // Normalizing the input
        return IntStream.range(0, str.length() / 2)
                        .allMatch(i -> str.charAt(i) == str.charAt(str.length() - i - 1));
    }
}

Output:

Is the string "Madam" a palindrome? true

Explanation:

  • The string is normalized by converting it to lowercase and removing non-alphanumeric characters.
  • An IntStream is used to iterate over the first half of the string.
  • The allMatch() method checks if all characters from the start and end of the string match.

4. Complete Example Program

Here is a complete program that demonstrates all the methods discussed above to check if a string is a palindrome.

Example Code:

import java.util.stream.IntStream;

public class PalindromeCheckExample {
    public static void main(String[] args) {
        String input = "A man, a plan, a canal, Panama";

        // Using a Simple Loop
        boolean resultLoop = isPalindromeUsingLoop(input);
        System.out.println("Using Simple Loop:");
        System.out.println("Is the string \"" + input + "\" a palindrome? " + resultLoop);

        // Using StringBuilder's reverse() Method
        boolean resultStringBuilder = isPalindromeUsingStringBuilder(input);
        System.out.println("\nUsing StringBuilder's reverse() Method:");
        System.out.println("Is the string \"" + input + "\" a palindrome? " + resultStringBuilder);

        // Using Java 8 Streams
        boolean resultStreams = isPalindromeUsingStreams(input);
        System.out.println("\nUsing Java 8 Streams:");
        System.out.println("Is the string \"" + input + "\" a palindrome? " + resultStreams);
    }

    public static boolean isPalindromeUsingLoop(String str) {
        str = str.toLowerCase().replaceAll("[^a-zA-Z0-9]", ""); // Normalizing the input
        int left = 0;
        int right = str.length() - 1;

        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }

    public static boolean isPalindromeUsingStringBuilder(String str) {
        str = str.toLowerCase().replaceAll("[^a-zA-Z0-9]", ""); // Normalizing the input
        String reversedStr = new StringBuilder(str).reverse().toString();
        return str.equals(reversedStr);
    }

    public static boolean isPalindromeUsingStreams(String str) {
        str = str.toLowerCase().replaceAll("[^a-zA-Z0-9]", ""); // Normalizing the input
        return IntStream.range(0, str.length() / 2)
                        .allMatch(i -> str.charAt(i) == str.charAt(str.length() - i - 1));
    }
}

Output:

Using Simple Loop:
Is the string "A man, a plan, a canal, Panama" a palindrome? true

Using StringBuilder's reverse() Method:
Is the string "A man, a plan, a canal, Panama" a palindrome? true

Using Java 8 Streams:
Is the string "A man, a plan, a canal, Panama" a palindrome? true

5. Conclusion

Checking if a string is a palindrome can be accomplished in multiple ways in Java. The simple loop method is straightforward and easy to understand, while the StringBuilder's reverse() method provides a quick and concise solution. Java 8 Streams offer a modern, functional programming approach to the same problem.

By understanding these different methods, you can choose the one that best fits your needs and coding style. Happy coding!

My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare