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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package com.javacodeexamples.basic; public class CheckIfStringIsPalindromeExample { public static void main(String[] args) { String[] strInputs = { "Hello World", "123321", "Madam", "Anna", "Bob", "Rise to vote sir", "Java Example" }; for(String str : strInputs){ System.out.println(str + ": " + isPalindrome(str)); } } private static boolean isPalindrome(String str) { /* * compare string with the reverse of it. * if they are equal, String is a Palindrome */ return str.equalsIgnoreCase( new StringBuilder(str).reverse().toString() ); } } |
Output
1 2 3 4 5 6 7 |
Hello World: false 123321: true Madam: true Anna: true Bob: true Rise to vote sir: false Java Example: false |
If you want to ignore the space, punctuations, and word separators, you can change the isPalindrome
method as given below.
1 2 3 4 5 6 7 8 9 10 11 12 |
private static boolean isPalindrome(String str) { //clean up the string str = str.replaceAll("[^a-zA-Z0-9]", ""); /* * compare string with the reverse of it. * if they are equal, String is a Palindrome */ return str.trim().equalsIgnoreCase( new StringBuilder(str.trim()).reverse().toString() ); } |
Output
1 2 3 4 5 6 7 |
Hello World: false 123321: true Madam: true Anna: true Bob: true Rise to vote sir: true Java Example: false |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
private static boolean isPalindrome(String str) { //clean up the string str = str.toLowerCase().replaceAll("[^a-zA-Z0-9]", ""); int length = str.length(); if(length == 0 || length == 1) return true; for(int i = 0; i < (length/2) ; i++){ if( str.charAt(i) != str.charAt(length - 1 - i) ) return false; } return true; } |
Output
1 2 3 4 5 6 7 |
Hello World: false 123321: true Madam: true Anna: true Bob: true Rise to vote sir: true Java Example: false |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
package com.javacodeexamples.basic; public class CheckIfStringIsPalindromeExample { public static void main(String[] args) { String[] strInputs = { "Hello World", "123321", "Madam", "Anna", "Bob", "Rise to vote sir", "Java Example", }; for(String str : strInputs){ System.out.println(str + ": " + isPalindrome(str.toLowerCase().replaceAll("[^a-zA-Z0-9]", ""))); } } private static boolean isPalindrome(String str) { int length = str.length(); if(length == 0 || length == 1) return true; if(str.charAt(0) == str.charAt(length - 1)) return isPalindrome( str.substring(1, length - 1) ); return false; } } |
Output
1 2 3 4 5 6 7 |
Hello World: false 123321: true Madam: true Anna: true Bob: true Rise to vote sir: true Java Example: false |
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.