How to find or check palindrome String in java

Many times we asked to write a code for checking palindrome string or words in java. Questions might be different such as How would you write a code in java to test for palindromes? How to check if a string is a palindrome in java? Write Java program for checking String is palindrome or not? Writing a java program to check palindrome String is often asked to new graduates and also in ISC students. Now lets see how we can check the String or word is palindrome or not.

Java Example for checking String is palindrome String



In the following example, I would like to share two methods to check the String is palindrome or not. In first method using the character array we are checking each characters from both sides, if any of the character do not matches then we are returning false. If the length is odd then checking the center letter doesn't matter because it doesn't need to compare.
In the second method we are using reverse method from the StringBuffer to reverse the String and we are matching the String with the reversed String if both Strings are equal then this String is palindrome String.

 
public class StringPalindromeTest {

public static void main(String[] args) {
String testWord = "aibohphobia";//"test"
if( istPalindromeString( testWord ) ){
System.out.println( "testWord : "+testWord+ " is a palindrome string" );
}else{
System.out.println( "testWord : "+testWord+ " is not a palindrome string" );
}
if( isPalindromeUsingReverse( testWord ) ){
System.out.println( "testWord : "+testWord+ " is a palindrome string" );
}else{
System.out.println( "testWord : "+testWord+ " is not a palindrome string" );
}
}

public static boolean istPalindromeString( String word ){
char[] charFromWord = word.toCharArray();// Converting String to character array
int startLength = 0;
int endLength = word.length() - 1; //Getting length of the string
while ( endLength > startLength ) {
//Checking characters from both sides
if ( charFromWord[ startLength ] != charFromWord[ endLength ] ) {
return false;
}
++startLength;
--endLength;
}
return true;
}

public static boolean isPalindromeUsingReverse( String word ) {
// In this method we are doing reverse of the word and checking for equality
return word.equals(new StringBuffer().append(word).reverse().toString());
}
}


Output :

testWord : aibohphobia is a palindrome string
testWord : aibohphobia is a palindrome string

testWord : test is not a palindrome string
testWord : test is not a palindrome string
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment