A palindrome is a sequence of characters (such as a word, phrase, number, or any other sequence) that reads the same forward and backward, disregarding spaces, punctuation, and capitalization. For example, "radar," "level," and "12321" are all palindromes.
To check whether a given string is a palindrome, you need to compare its characters from both ends inward and ensure that they match.
Here's the Java code to check if a given string is a palindrome:
public class PalindromeCheck {
public static void main(String[] args) {
String input = "radar"; // Change this string to test different cases
boolean isPalindrome = checkPalindrome(input);
if (isPalindrome) {
System.out.println("'" + input + "' is a palindrome.");
} else {
System.out.println("'" + input + "' is not a palindrome.");
}
}
public static boolean checkPalindrome(String str) {
str = str.toLowerCase(); // Convert to lowercase for case-insensitive comparison
int left = 0;
int right = str.length() - 1;
while (left < right) {
char leftChar = str.charAt(left);
char rightChar = str.charAt(right);
if (leftChar != rightChar) {
return false;
}
left++;
right--;
}
return true;
}
}
No comments:
Post a Comment