A palindrome is a word, phrase, number or other sequence of characters that reads the same backward as forward. Here is an example of how to check if a string is a palindrome in Java:
public static boolean isPalindrome(String str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
This method takes a string as input and returns true if it is a palindrome and false otherwise. It works by comparing the characters at the beginning and end of the string, moving inward until the entire string has been checked.
Here’s an example of how to use the isPalindrome method:
String str1 = "racecar";
String str2 = "hello";
if (isPalindrome(str1)) {
System.out.println(str1 + " is a palindrome");
} else {
System.out.println(str1 + " is not a palindrome");
}
if (isPalindrome(str2)) {
System.out.println(str2 + " is a palindrome");
} else {
System.out.println(str2 + " is not a palindrome");
}
This code will output:
racecar is a palindrome
hello is not a palindrome
Note that the isPalindrome method is case-sensitive, so “Racecar” would not be considered a palindrome. If you want to ignore case, you can convert the string to lowercase or uppercase before checking.