Page Contents
What is Palindrome ?
A string is a palindrome if the position of each character is the same even if the string is reversed. For example, “NAMAN” is a palindrome because the position of each character is the same even if the string “NAMAN” is reversed. Here we can use the predefined library method or not, to identify a string as palindrome
Example – check if a given String is palindrome
public class PalindromeStringChecker {
public static void main(String[] args) {
String strValue = "NAMAN";
StringBuffer newStrValue = new StringBuffer();
for (int i = strValue.length() - 1; i >= 0; i--) {
newStrValue = newStrValue.append(strValue.charAt(i));
}
if (strValue.equalsIgnoreCase(newStrValue.toString())) {
System.out.println(strValue + " is a palindrome String");
} else {
System.out.println(strValue + " is not a palindrome String");
}
}
}
Output
NAMAN is a palindrome String
Example – check if a given String is palindrome using reverse method
public class PalindromeStringCheker {
public static void main(String[] args) {
String strValue = "NAMAN";
String reverseString = new StringBuffer(strValue).reverse()+"";
if (strValue.equals(reverseString)) {
System.out.println(strValue + " is palindrome String");
} else {
System.out.println(strValue + " is not palindrome String");
}
}
}
Output
NAMAN is palindrome String
Example – Just another way
public class PalindromStringCheker {
public static void main(String args[]) {
String currentValue = "";
String compareValue = "";
currentValue = "545";
int length = currentValue.length();
for (int i = length - 1; i >= 0; i--)
compareValue = compareValue + currentValue.charAt(i);
if (currentValue.equals(compareValue)) {
System.out.println(currentValue + " is a palindrome.");
} else {
System.out.println(currentValue + " is not a palindrome.");
}
}
}
Output
545 is a palindrome.
Example
In above program, If: currentValue= "553" Output: 553 is not a palindrome. If: currentValue= “proedu” Output: proedu is not a palindrome.