Skip to content

Check if a String is Palindrome in Java Example

This example shows how to check if a string is a palindrome in Java using recursion and the StringBuffer or StringBuilder class.

What is a palindrome?

From Wikipedia,

A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward.

You may ignore the case, punctuations, and word dividers while determining a palindrome.

How to check if the string is a palindrome in Java?

Basically, we need to compare a string with the reverse of it to determine if a string is a palindrome. There are several ways in which you can check if a String is a palindrome in Java as given below.

1) Check if a String is a Palindrome using StringBuffer or StringBuilder

This is the simplest approach of all. It reverses a string using the reverse method of the StringBuffer/StringBuilder class to determine if a string is a palindrome.

Output

If you want to ignore the space, punctuations, and word separators, you can change the isPalindrome  method as given below.

Output

Note: If you are using Java 1.4 or a lower version of Java, use the StringBuffer class instead of the StringBuilder class.

2) Using the charAt method of the String class

If you don’t want to use StringBuffer/StringBuilder classes or looking for a more efficient method, you can do it using the charAt method of the String class as given below.

Output

Basically, we are comparing the first character of the string with the last character, the second character with the second last, and so on until the characters are not equal. We also don’t go up to the string length, we only scan the first half of the string and compare it with the second half. If any of the characters do not match, we return false.

3) Using recursion

While not recommended, we can check if a string is a palindrome using the recursive function or recursive method as given below.

Output

All 0 and 1 length strings are palindrome by default, so we are returning true for them and thus stopping the recursive calls. If not, we check if the first and last characters of the strings are equal. If they are, we call the same method with one character removed from both sides of the string. If they are not equal, we do not call the recursive method and return false.

This example is a part of the Java Basic Examples.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.