Java Basic Examples

Check if a String is Palindrome in Java Example

This Example shows how to check if a string is palindrome in Java. It also shows how to check if a string is palindrome using recursion and StringBuffer/StringBuilder.

What is 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 String is Palindrome in Java?

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

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

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

Output

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

Output

Note:

If you are using Java 1.4 or lesser version of Java, use StringBuffer instead of StringBuilder class.

2) Check if a String is Palindrome using charAt method of String class

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

Output

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

3) Check if a String is Palindrome using Recursion

While not recommended, we can check if a String is Palindrome using recursive function as given below.

Output

All 0 and 1 length Strings are palindrome by default, so we are returning true 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.

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

 

Tags
Join 1000+ fellow learners! Enter your email address below: