Check if a string is a palindrome

Description: A palindrome reads the same from both sides, like madam. Write isPalindrome(String s) which ignores the case and the spaces. Test it with “Madam”, “Nurses run” and “Java”.

Hint:

  • Clean the text with replace(" ", "") and toLowerCase(), then compare it with its reverse.

Solution

public class Main {
    static boolean isPalindrome(String s) {
        String clean = s.replace(" ", "").toLowerCase();
        String reversed = new StringBuilder(clean).reverse().toString();
        return clean.equals(reversed);
    }

    public static void main(String[] args) {
        for (String text : new String[]{"Madam", "Nurses run", "Java"}) {
            System.out.println(text + " -> " + isPalindrome(text));
        }
    }
}
Output

Madam -> true
Nurses run -> true
Java -> false

How it works

  • We remove the spaces and use one case, so only the letters are compared.
  • equals() compares the text. Do not use ==.

Read Java Strings.


Learn more about the similar topics:
Tutorials
Java Strings
Java String Methods
Java StringBuilder and Text Blocks
Exercises & Assignments
Reverse a string
Check if a string is a palindrome
Count the vowels in a string
Interview Questions & Answers
What is the difference between == and equals() in Java?
Why is String immutable in Java?
What is the difference between String, StringBuilder and StringBuffer?
What is the string pool in Java and what does intern() do?