Palindrome Checker in Java
A palindrome is a word, phrase, number, or other sequences of characters which reads the same backward as forward (ignoring spaces, punctuation, and capitalization). For example, “madam” and “racecar” are palindromes.
This program checks if a given string is a palindrome using the Java programming language.
Java Program
/**
* Palindrome Checker: Check if a given string is a palindrome.
*/
public class PalindromeChecker {
/**
* Method to check if the input string is a palindrome.
*
* @param str the input string to check
* @return true if the input string is a palindrome, false otherwise
*/
public static boolean isPalindrome(String str) {
// Removing all non-alphanumeric characters and converting to lower case
String cleanedStr = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
// Initializing pointers for start and end of the string
int left = 0;
int right = cleanedStr.length() - 1;
// Comparing characters from start and end
while (left < right) {
if (cleanedStr.charAt(left) != cleanedStr.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
/**
* Main method to run the Palindrome Checker.
*
* @param args command-line arguments (not used)
*/
public static void main(String[] args) {
String[] testStrings = {
"madam",
"racecar",
"A man, a plan, a canal, Panama",
"No lemon, no melon",
"Hello, World!"
};
for (String s : testStrings) {
System.out.println("\"" + s + "\" is " + (isPalindrome(s) ? "" : "not ") + "a palindrome.");
}
}
}
Explanation
The program consists of two methods:
isPalindrome
: This method takes a string as input and checks if it is a palindrome. It does the following:- Removes all non-alphanumeric characters and converts the string to lowercase to ensure uniformity.
- Initializes two pointers: one at the start (left) and one at the end (right) of the cleaned string.
- Compares characters at these pointers. If they do not match, the string is not a palindrome. If they match, the pointers move towards the center.
- If all characters match as the pointers move towards the center, the string is a palindrome.
main
: This method tests theisPalindrome
method with several example strings, printing the results to the console.
Output
Running the above program will produce the following output:
"madam" is a palindrome.
"racecar" is a palindrome.
"A man, a plan, a canal, Panama" is a palindrome.
"No lemon, no melon" is a palindrome.
"Hello, World!" is not a palindrome.