You are currently viewing Checking if a String is Palindrome in Java

Checking if a String is Palindrome in Java

A palindrome is a sequence of characters that reads the same forward and backward. In simpler terms, it’s like a word or phrase that remains unchanged when its order is reversed. Understanding how to check if a string is a palindrome is a fundamental concept in programming, especially when dealing with tasks related to string manipulation and algorithmic problem-solving.

Defining Palindrome

Before delving into the code, let’s establish a clear understanding of what a palindrome is. In its simplest form, a palindrome is a string that remains the same when read backward. It ignores spaces, punctuation, and capitalization, focusing solely on the sequence of letters. For example, “radar” and “level” are palindromes, while “hello” and “world” are not.

Simple Palindrome Check in Java

Let’s start our journey by examining a basic Java program to check whether a string is a palindrome. In its essence, palindrome checking involves comparing characters from the beginning and end of a string, gradually moving towards the center.

import java.util.Scanner;

public class PalindromeChecker {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a string: ");
        String input = scanner.nextLine();

        if (isPalindrome(input)) {
            System.out.println("Yes, it's a palindrome!");
        } else {
            System.out.println("No, it's not a palindrome.");
        }
        
    }

    private static boolean isPalindrome(String str) {

        str = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
        int length = str.length();

        for (int i = 0; i < length / 2; i++) {
            if (str.charAt(i) != str.charAt(length - i - 1)) {
                return false;
            }
        }

        return true;

    }
}

This straightforward Java program prompts the user to input a string and then checks whether it is a palindrome. The isPalindrome method takes care of the actual palindrome checking logic. It first removes non-alphanumeric characters and converts the string to lowercase for a case-insensitive check. The loop then compares characters from the beginning and end until reaching the middle of the string.

Handling Palindromes with StringBuilder

Another approach to tackle palindrome checking involves utilizing the StringBuilder class in Java. Let’s explore how this alternative method works:

import java.util.Scanner;

public class PalindromeCheckerStringBuilder {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a string: ");
        String input = scanner.nextLine();

        if (isPalindrome(input)) {
            System.out.println("Yes, it's a palindrome!");
        } else {
            System.out.println("No, it's not a palindrome.");
        }

    }

    private static boolean isPalindrome(String str) {

        str = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
        StringBuilder reversed = new StringBuilder(str).reverse();

        return str.equals(reversed.toString());

    }

}

In this version, we leverage the StringBuilder class to reverse the input string and then compare it with the original string. This approach offers a concise and readable solution to the palindrome-checking problem.

Handling Palindromes with Recursion

Now, let’s explore a recursive approach to checking for palindromes in Java. Recursion is a powerful technique where a function calls itself to solve a smaller instance of the problem.

import java.util.Scanner;

public class PalindromeCheckerRecursive {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a string: ");
        String input = scanner.nextLine();

        if (isPalindrome(input)) {
            System.out.println("Yes, it's a palindrome!");
        } else {
            System.out.println("No, it's not a palindrome.");
        }
    }

    private static boolean isPalindrome(String str) {

        str = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
        int length = str.length();

        if (length <= 1) {
            return true;
        } else if (str.charAt(0) != str.charAt(length - 1)) {
            return false;
        } else {
            return isPalindrome(str.substring(1, length - 1));
        }
    }
}

In this version, the isPalindrome method recursively checks whether the first and last characters of the string are equal. If they are, the function continues to check the inner substring until the base case is reached. This recursive approach provides another perspective on solving the palindrome problem.

Conclusion

In the realm of Java programming, checking whether a string is a palindrome is not only a fascinating problem but also an exercise in string manipulation and logical thinking. We have explored three different approaches to tackle this challenge: the basic iterative approach, the StringBuilder method, and a recursive solution.

By understanding and implementing these methods, you not only enhance your Java programming skills but also gain valuable insights into problem-solving techniques. The ability to work with strings, iterate through characters, and apply recursion are fundamental skills that can be extended to a wide array of programming challenges. For more content, please subscribe to our newsletter.

Leave a Reply