Java program to check a given string is Palindrome

In this post we will learn one of the interview programming question to check given string is a palindrome or not.

Lets assume input string is "MADAM" and we will write a program to check whether "MADAM" is a palindrome or not.
In order to check a given string is palindrome we first need to reverse the given string and compare both original and reverse string if both are same then we can say given string is a palindrome. 

package com.ekumeedhelp;

public class Palindrome {

public static void main(String[] args) {

if (isPalindrome("MADAM")) {
System.out.println("Given String is a palindrome");
} else {
System.out.println("Given String isn't a palindrome");
}
}

public static boolean isPalindrome(String original) {

String reversed = "";
int length = original.length();

for (int i = 0; i < length; i++)
reversed = reversed + original.charAt(length - i - 1);

if (original.equals(reversed))
return true;

return false;
}
}


Another way to solve the same problem. I would say this is most elegant way

package com.ekumeedhelp;

public class Palindrome {

public static void main(String[] args) {

if (isPalindrome("MADAM")) {
System.out.println("Given String is a palindrome");
} else {
System.out.println("Given String isn't a palindrome");
}
}

public static boolean isPalindrome(String s) {

int i = 0;
int j = s.length() - 1;
int k = (i + j) / 2;

for (int index = 1; index <= k; index++) {
if (s.charAt(i) == s.charAt(j)) {
i++;
j--;
} else
return false;
}
return true;
}
}