Write code to check a String is palindrome or not

In java there are two ways to check a String is palindrome or not. First one is using simple stringBuffer. Reverse the StringBuffer and equalize. The second method is to traverse through the String, make a revered String and then equalize. Both examples are given below,

Using StringBuffer:

public boolean isPalindron(String str){
StringBuffer buff = new StringBuffer(str);
return buff.reverse().toString().equalsIgnoreCase(str);

Using Loop:

public boolean isPalindron(String str){
if(str == null){
return false;
String reversedStr = new String();
for (int i = str.length()-1; i >= 0; i--) {
reversedStr = reversedStr + str.charAt(i);

return str.equalsIgnoreCase(reversedStr);

3 Comments Add yours

  1. ketan says:

    Instead of traversing the whole string you can loop till the half of its length and for each iteration you can compare the first and last character(first char and last char then second char and second last char), if anyone does not matches then its not a palindron, correct me if I am wrong.

    1. Abhinaba Basu says:

      no u r correct… that is more optimized code…

    2. Bharat says:

      what if there is a odd number of characters are there in palindrome string ?
      in that case you have to leave that middle character and apply your logic of comparing first with the last and second with second last !

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s