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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/inner_classes("`Inner Classes`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/packages_api("`Packages / API`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/wrapper_classes("`Wrapper Classes`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/booleans("`Booleans`") java/BasicSyntaxGroup -.-> java/comments("`Comments`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/for_loop("`For Loop`") java/BasicSyntaxGroup -.-> java/if_else("`If...Else`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/BasicSyntaxGroup -.-> java/while_loop("`While Loop`") java/SystemandDataProcessingGroup -.-> java/string_methods("`String Methods`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/scope -.-> lab-117978{{"`Checking Palindromes in Java`"}} java/inner_classes -.-> lab-117978{{"`Checking Palindromes in Java`"}} java/classes_objects -.-> lab-117978{{"`Checking Palindromes in Java`"}} java/class_methods -.-> lab-117978{{"`Checking Palindromes in Java`"}} java/modifiers -.-> lab-117978{{"`Checking Palindromes in Java`"}} java/oop -.-> lab-117978{{"`Checking Palindromes in Java`"}} java/packages_api -.-> lab-117978{{"`Checking Palindromes in Java`"}} java/wrapper_classes -.-> lab-117978{{"`Checking Palindromes in Java`"}} java/identifier -.-> lab-117978{{"`Checking Palindromes in Java`"}} java/arrays -.-> lab-117978{{"`Checking Palindromes in Java`"}} java/booleans -.-> lab-117978{{"`Checking Palindromes in Java`"}} java/comments -.-> lab-117978{{"`Checking Palindromes in Java`"}} java/data_types -.-> lab-117978{{"`Checking Palindromes in Java`"}} java/for_loop -.-> lab-117978{{"`Checking Palindromes in Java`"}} java/if_else -.-> lab-117978{{"`Checking Palindromes in Java`"}} java/operators -.-> lab-117978{{"`Checking Palindromes in Java`"}} java/output -.-> lab-117978{{"`Checking Palindromes in Java`"}} java/strings -.-> lab-117978{{"`Checking Palindromes in Java`"}} java/variables -.-> lab-117978{{"`Checking Palindromes in Java`"}} java/while_loop -.-> lab-117978{{"`Checking Palindromes in Java`"}} java/string_methods -.-> lab-117978{{"`Checking Palindromes in Java`"}} java/system_methods -.-> lab-117978{{"`Checking Palindromes in Java`"}} end

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