How to check String is Palindrome or not in Java?

UPDATED: 04 February 2015
Palindrome
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward. Like 121 <-reverse-> 121, aba <-reverse-> aba, etc...

Source Code
public class PalindromeString {

    public static void main(String[] args) {
        String str = "aba";
        PalindromeString objPalindromeString = new PalindromeString();
        System.out.println("Is \"" + str + "\" Palindrome?");
        System.out.println(objPalindromeString.isPalindromeString(str));
    }

    /**
     * @author javaQuery
     * @param str
     * @return {@link boolean}
     * 
     * Method is used to check String is Palindrome or not.
     */
    public boolean isPalindromeString(String str) {
        /* If its null then return false */
        if (str == null) {
            return false;
        }
        /* Use StringBuilder/StringBuffer to reverse the String */
        StringBuilder strBuilder = new StringBuilder(str);
        strBuilder.reverse();
        /* Compare original and reversed String */
        return str.equalsIgnoreCase(strBuilder.toString());
    }
}

Output
Is "aba" Palindrome?
true

0 comments :