Java Program To Check Palindrome String

A palindrome is a sequence of characters that reads the same forward and backward. Common examples include words like "level," "radar," or "racecar." In software development, checking for palindromes is a classic algorithmic challenge often used to test a developer's understanding of string manipulation and loops.

The most efficient way to solve this in Java is by using the Two-Pointer Technique. Instead of creating a copy of the string (which consumes extra memory), we compare characters from both ends and move toward the center.

public class PalindromeChecker {
    public static void main(String[] args) {
        // You can change this to test different words
        String word = "Racecar"; 
        
        if (isPalindrome(word)) {
            System.out.println("The string \"" + word + "\" is a palindrome.");
        } else {
            System.out.println("The string \"" + word + "\" is not a palindrome.");
        }
    }

    /**
     * Checks if a string is a palindrome using the two-pointer approach.
     * This method is case-insensitive.
     */
    public static boolean isPalindrome(String str) {
        // Return true if string is null or empty (based on requirements)
        if (str == null || str.isEmpty()) {
            return true;
        }

        // Convert to lowercase to ensure 'M' and 'm' are treated as the same
        str = str.toLowerCase();

        int left = 0;
        int right = str.length() - 1;

        // Loop until the pointers meet in the middle
        while (left < right) {
            // Compare characters at both ends
            if (str.charAt(left) != str.charAt(right)) {
                return false; // Not a palindrome
            }
            
            // Increment left pointer, decrement right pointer
            left++;
            right--;
        }
        
        return true; // Successfully matched all characters
    }
}
Best Practice: Always handle case sensitivity. To a computer, 'A' and 'a' are different characters. Using .toLowerCase() ensures your check is user-friendly and accurate for natural language words.

This program defines a method isPalindrome that checks if the given string is a palindrome by comparing characters from both ends of the string. The main method calls this function with a sample string and prints the result.

How the Logic Works

The two-pointer approach is highly efficient because it has a time complexity of O(n) and a space complexity of O(1) (assuming we don't count the input string itself). Here is the step-by-step logic:

  1. Initialize Pointers: We set left to 0 (the start of the string) and right to length - 1 (the end of the string).
  2. Comparison: We compare the character at str.charAt(left) with str.charAt(right).
  3. Looping: If they match, we move left one step forward and right one step backward.
  4. Early Exit: If at any point the characters don't match, we immediately return false.
  5. Success: If the pointers meet or cross without a mismatch, the string is a palindrome.
Developer Tip: In a real-world application (like a search engine or a text processor), you might want to strip out spaces and punctuation using regex before checking for a palindrome. For example: str.replaceAll("[^a-zA-Z0-9]", "").
Common Mistake: Forgetting that str.length() returns the total count, but index starts at 0. Always set your right pointer to str.length() - 1 to avoid an IndexOutOfBoundsException.

Practical Real-World Examples

While checking for "madam" is a great exercise, palindrome logic appears in several practical development scenarios:

  • Data Integrity: Detecting symmetrical patterns in data streams or DNA sequencing (bioinformatics).
  • UI/UX Features: Creating "Undo" logic where a sequence of actions must be reversible or verifiable from both ends.
  • Input Validation: Verifying specialized ID formats or serial numbers that follow a mirrored structure for redundancy.
Watch Out: Be careful with null values. If you call .length() on a null string, your program will crash. Always check if (str == null) at the beginning of your methods.

Alternative Approach: StringBuilder

If you prefer a more concise (though slightly less memory-efficient) method, you can use the StringBuilder class:

public static boolean isPalindromeEasy(String str) {
    String reversed = new StringBuilder(str).reverse().toString();
    return str.equalsIgnoreCase(reversed);
}
Developer Tip: Use the two-pointer method for technical interviews or high-performance apps. Use the StringBuilder.reverse() method for quick scripts or when performance isn't a critical bottleneck, as it makes the code much easier to read.