Introduction
In this tutorial I will check how to verify a string is palindrome or not using Java programming language.
A palindrome is a technique, where a word, phrase, or sequence that reads the same backwards as forwards. For example, ehcache, madam, etc are examples of palindrome.
Prerequisites
Java
Check Palindrome
I will use here few techniques to present how to check a string is palindrome or not.
1st Approach
In first approach, I will use while loop to extract each char from the given string to test for palindrome.
public static boolean isPalindromUsingIndex(final String str) {
int firstIndex = 0;
int lastIndex = str.length() - 1;
boolean result = true;
while (true) {
if (firstIndex >= lastIndex) {
break;
}
char first = str.charAt(firstIndex);
char last = str.charAt(lastIndex);
if (first != last) {
result = false;
break;
}
firstIndex++;
lastIndex--;
}
return result;
}
2nd Approach
In second approach, I will use while loop and charAt()
method as I have used in the previous example but in different way.
public static boolean isPalindromUsingCharAt(final String str) {
int right = 0;
int left = 1;
int len = str.length();
while (str.charAt(right) == str.charAt(len - left) && left < (len / 2)) {
left++;
right++;
}
if (str.charAt(right) == str.charAt(len - left)) {
return true;
}
return false;
}
3rd Approach
In this approach, I will use length()
, charAt()
and for loop to determine palindrome.
public static boolean isPalindromUsingLength(final String str) {
int l = str.length();
char[] chars = new char[l];
for (int j = l - 1; j > -1; j--) {
chars[l - j - 1] = (str.charAt(j));
}
if (str.equals(String.valueOf(chars))) {
return true;
}
return false;
}
4th Approach
I will determine whether a string is palindrome or not by iterating only half of the given string’s length.
public static boolean isPalindromUsingHalfLength(final String str) {
int len = str.length();
for (int i = 0; i < len / 2; i++) {
if (str.charAt(i) != str.charAt(len - i - 1)) {
return false;
}
}
return true;
}
5th Approach
Now I will verify using the reverse()
method of the StringBuffer
or StringBuilder
class.
Remember String class does not have reverse()
method as it is a final class.
public static boolean isPalindromUsingReverse(final String str) {
StringBuilder sb = new StringBuilder(str);
// StringBuffer sb = new StringBuffer(str);
if (str.equals(sb.reverse().toString())) {
return true;
}
return false;
}
Testing Palindrome
Now creating a main method in the class and executing the main method by calling the above methods for checking palindrome will give you the expected output.
public static void main(String[] args) {
System.out.println(isPalindromUsingIndex("ehcache"));
System.out.println(isPalindromUsingCharAt("ehcache"));
System.out.println(isPalindromUsingLength("ehcache"));
System.out.println(isPalindromUsingReverse("ehcache"));
System.out.println(isPalindromUsingHalfLength("ehcache"));
}
Running the above code will give you below output:
true
true
true
true
true