String Palindrome in Java: Solution, Explanation & Practice

Check if a string is a palindrome

Problem summary

Write a program that checks if a string is a palindrome (reads same forwards and backwards).

Starter code

public class Main {
    public static void main(String[] args) {
        String text = "madam"; // Test case 1
        
        // Check if palindrome (ignore case)
        // Print: Is palindrome: <true/false>
    }
}

Expected output and test cases

  • madam is palindrome
    Is palindrome: true
  • Racecar (ignore case)
    Is palindrome: true
  • Hello is not
    Is palindrome: false

Hints

  1. Compare characters from both ends
  2. Use toLowerCase() for case-insensitive
  3. Or reverse and compare with original

Validated solution

Reveal Java solution
public class Main {
    static boolean isPalindrome(String text) {
        int left = 0, right = text.length() - 1;
        while (left < right) {
            if (Character.toLowerCase(text.charAt(left)) != Character.toLowerCase(text.charAt(right))) return false;
            left++; right--;
        }
        return true;
    }
    public static void main(String[] args) {
        System.out.println("Is palindrome: " + isPalindrome("madam"));
    }
}

How to approach the problem

Compare mirrored characters instead of building a reversed copy. Lowercasing each compared character gives the exercise’s case-insensitive behavior without modifying the original String.

Approach

  1. Place one pointer at each end.
  2. Compare normalized mirrored characters.
  3. Stop at the first mismatch or when pointers meet.

Time and space complexity

Time: O(n). Space: O(1).

Edge cases to test

  • Empty and one-character strings are palindromes.
  • This version ignores case but not punctuation or spaces.

Common mistakes

  • Comparing Strings with == instead of character values or equals.
  • Making an unstated choice about punctuation.

Follow-up challenge

Extend the method to ignore non-alphanumeric characters.

Related Strings exercises

Practice all Strings exercises · Run this idea in the Java compiler