Checking Palindromes in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, we will learn how to check whether a string is a palindrome or not in Java. A palindrome is a string which reads the same forwards and backward.

Using Two Pointers to Check for Palindromes

The first method we will implement is the two-pointer approach. We will create a method called isPalindrome which takes a string as input and returns a boolean value indicating whether the string is a palindrome or not.

public class PalindromeChecker {
    public static boolean isPalindrome(String str) {
        int start = 0;
        int end = str.length() - 1;

        while (start < end) {
            char startChar = Character.toLowerCase(str.charAt(start));
            char endChar = Character.toLowerCase(str.charAt(end));

            if (startChar != endChar) {
                return false;
            }

            start++;
            end--;
        }

        return true;
    }
}

The isPalindrome method uses two pointers, start and end, which start from the beginning and end of the string respectively. The loop runs until the two pointers meet in the middle.

At each iteration, we compare the characters at the start and end pointers. If they are not equal, we return false. If they are, we update the pointers to check the next set of characters in the string.

To test our method, we can add a main method and call the isPalindrome method with various input strings.

public class PalindromeChecker {
    public static boolean isPalindrome(String str) {
        // Implementation of isPalindrome method
    }

    public static void main(String[] args) {
        System.out.println("Is 'racecar' a palindrome? " + isPalindrome("racecar"));
        System.out.println("Is 'hello' a palindrome? " + isPalindrome("hello"));
    }
}

Using Recursion to Check for Palindromes

The next method we will implement is the recursive approach. We will create a new method called isPalindromeRecursive which takes the string, start index, and end index as input.

public class PalindromeChecker {
    public static boolean isPalindrome(String str) {
        String lowercaseStr = str.toLowerCase();
        return isPalindromeRecursive(lowercaseStr, 0, lowercaseStr.length() - 1);
    }

    public static boolean isPalindromeRecursive(String str, int start, int end) {
        if(start >= end) {
            return true;
        }

        char startChar = Character.toLowerCase(str.charAt(start));
        char endChar = Character.toLowerCase(str.charAt(end));

        if(startChar != endChar) {
            return false;
        }

        return isPalindromeRecursive(str, start + 1, end - 1);
    }

    public static void main(String[] args) {
        // Tests for isPalindrome and isPalindromeRecursive methods
    }
}

The isPalindromeRecursive method uses recursion to check if the string is a palindrome or not. We have two base cases:

  1. If the start index is greater than or equal to the end index, it means we have checked all the characters in the string and they match, so we return true.
  2. If the characters at the start and end indices are not equal, we return false.

If neither of the base cases is met, we call isPalindromeRecursive again with the updated indices.

We can now test our recursive method by calling it inside the main method.

public class PalindromeChecker {
    public static boolean isPalindrome(String str) {
        // Implementation of isPalindrome method
    }

    public static boolean isPalindromeRecursive(String str, int start, int end) {
        // Implementation of isPalindromeRecursive method
    }

    public static void main(String[] args) {
        System.out.println("Is 'racecar' a palindrome? " + isPalindromeRecursive("racecar", 0, 6));
        System.out.println("Is 'hello' a palindrome? " + isPalindromeRecursive("hello", 0, 4));
    }
}

Reversing the String to Check for Palindromes

The last method we will implement is the string reversal approach. We will create a new method called isPalindromeReverse which takes a string as input.

public class PalindromeChecker {
    public static boolean isPalindrome(String str) {
        // Implementation of isPalindrome method
    }

    public static boolean isPalindromeRecursive(String str, int start, int end) {
        // Implementation of isPalindromeRecursive method
    }

    public static boolean isPalindromeReverse(String str) {
        String reversed = "";

        for (int i = str.length() - 1; i >= 0; i--) {
            reversed += str.charAt(i);
        }

        return str.equalsIgnoreCase(reversed);
    }

    public static void main(String[] args) {
        // Tests for isPalindrome and isPalindromeRecursive methods
        System.out.println("Is 'racecar' a palindrome? " + isPalindromeReverse("racecar"));
        System.out.println("Is 'hello' a palindrome? " + isPalindromeReverse("hello"));
    }
}

The isPalindromeReverse method creates a new string called reversed and populates it by iterating through the input string from the end to the beginning. We then return true if the two strings are equal ignoring case.

We can test the method by adding a call to isPalindromeReverse in the main method.

Using Java Streams to Check for Palindromes

Finally, we will use the Java Streams API to check for palindromes. We will create a new method called isPalindromeStream which takes a string as input.

import java.util.stream.IntStream;

public class PalindromeChecker {
    public static boolean isPalindrome(String str) {
        // Implementation of isPalindrome method
    }

    public static boolean isPalindromeRecursive(String str, int start, int end) {
        // Implementation of isPalindromeRecursive method
    }

    public static boolean isPalindromeReverse(String str) {
        // Implementation of isPalindromeReverse method
    }

    public static boolean isPalindromeStream(String str) {
        String lowercaseStr = str.toLowerCase();

        return IntStream.range(0, lowercaseStr.length() / 2)
                .noneMatch(i -> lowercaseStr.charAt(i) != lowercaseStr.charAt(lowercaseStr.length() - i - 1));
    }

    public static void main(String[] args) {
        // Tests for isPalindrome and isPalindromeRecursive methods
        System.out.println("Is 'racecar' a palindrome? " + isPalindromeStream("racecar"));
        System.out.println("Is 'hello' a palindrome? " + isPalindromeStream("hello"));
    }
}

The isPalindromeStream method uses the IntStream class to generate a range of indices which we can use to compare characters in the string.

We use the noneMatch method to return true if none of the characters violate the condition that the ith and n-i-1th characters are equal, where n is the length of the string and i is the index.

We can test the method by adding a call to isPalindromeStream in the main method.

Summary

In this lab, we learned how to check whether a given string is a palindrome or not in Java. We implemented four different methods to accomplish this task:

  1. Two-pointer approach
  2. Recursive approach
  3. Reversing the string approach
  4. Java Streams approach

Now that you understand these methods, you can use them to solve more complex problems!

Other Java Tutorials you may like