How do I determine whether a string is a palindrome?

This code checks a string to determine if it is a palindrome or not. A palindrome is a word, phrase, or sequence that reads the same backward as forward.

package org.kodejava.lang;

public class PalindromeChecker {

    public static void main(String[] args) {
        String text = "Sator Arepo Tenet Opera Rotas";

        PalindromeChecker checker = new PalindromeChecker();
        System.out.println("Is palindrome = " + checker.isPalindrome(text));
    }

    /**
     * This method checks the string for palindrome. We use StringBuilder to
     * reverse the original string.
     *
     * @param text a text to be checked for palindrome.
     * @return <code>true</code> if a text is palindrome.
     */
    private boolean isPalindrome(String text) {
        System.out.println("Original text = " + text);

        String reverse = new StringBuilder(text).reverse().toString();
        System.out.println("Reverse text  = " + reverse);

        // Compare the original text with the reverse one and ignoring its case
        return text.equalsIgnoreCase(reverse);
    }
}
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.