How to Check if a String is a Palindrome in Java

Are you familiar with the concept of palindromes? A palindrome is a word, phrase, number, or other sequence of characters that reads the same backward as forward. For example, “racecar” and “level” are palindromes. In this blog post, we will discuss how to check if a given string is a palindrome or not using Java programming language.

To start, let’s take a look at the code snippet below:

public static boolean isPalindrome(String str) {
// Remove non-alphanumeric characters and convert to lowercase
    str = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase(); 
    int left = 0;
    int right = str.length() - 1;
    while (left < right) {
        if (str.charAt(left) != str.charAt(right)) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}

This code defines a function called isPalindrome which takes a string as input and returns a boolean value indicating whether the string is a palindrome or not. Let’s go through each line of the code and understand what it does.

The first line of the function removes any non-alphanumeric characters from the input string using the replaceAll function. It replaces all characters that are not alphanumeric with an empty string. Then, it converts the resulting string to lowercase using the toLowerCase function. This step ensures that we can compare characters without worrying about case sensitivity and non-alphanumeric characters.

Next, we define two pointers left and right, which will traverse the string from both ends towards the middle. We initialize left to 0, which is the first character of the string, and right to the index of the last character of the string.

We then enter a while loop that continues until left and right pointers cross each other or meet in the middle. Inside the loop, we compare the character at the left pointer and the character at the right pointer. If they are not equal, it means that the string is not a palindrome, and we return false.

If the loop completes without returning false, it means that the string is a palindrome, and we return true.

Let’s now test the function with some sample inputs:

String str1 = "A man, a plan, a canal: Panama";
String str2 = "race a car";
System.out.println(isPalindrome(str1)); // true
System.out.println(isPalindrome(str2)); // false

In the first test, we pass the string “A man, a plan, a canal: Panama,” which is a palindrome, and the function returns true. In the second test, we pass the string “race a car,” which is not a palindrome, and the function returns false.

In conclusion, checking if a string is a palindrome or not in Java is a simple and straightforward process. By following the steps outlined in this blog post, you can easily write a function to determine if a given string is a palindrome or not. And to make your coding experience even more enjoyable, why not have a cute cat as your coding companion? Happy coding!

Leave a comment