Write a Java program that checks whether a string is a palindrome or not.
The provided Java program checks whether a string is a palindrome or not. A palindrome is a word or phrase that reads the same forward and backward (ignoring spaces, punctuation, and case).
class Main {
public static void main(String[] args) {
String str = "madam";
if (isPalindromeString(str)) {
System.out.print("is palindrome string.");
} else {
System.out.print("is not palindrome string");
}
}
public static boolean isPalindromeString(String str) {
str = str.toLowerCase(); // Convert string to lowercase for case-insensitive comparison
int start = 0;
int end = str.length() - 1;
while (start < end) {
if (str.charAt(start) != str.charAt(end)) {
return false; // If characters don't match, return false
}
start++;
end--;
}
return true; // If all character pairs match, return true
}
}
Output:
is palindrome string.
The provided Java program checks whether a string is a palindrome or not. A palindrome is a word or phrase that reads the same forward and backward (ignoring spaces, punctuation, and case). Here’s a breakdown of the code:
How It Works
- Input String:
- The input string is “madam”.
- isPalindromeString Method:
- The method converts the string to lowercase to ensure the comparison is case-insensitive (i.e., ‘M’ and ‘m’ are treated as the same).
- It uses two pointers: one starting at the beginning of the string (start) and the other at the end (end).
- The method compares the characters at start and end. If they are not equal, it returns false (i.e., the string is not a palindrome).
- If all corresponding characters match, it returns true (i.e., the string is a palindrome).
Execution:
- Convert string to lowercase: “madam”
- Compare characters from both ends:
- ‘m’ == ‘m’ (start = 0, end = 4)
- ‘a’ == ‘a’ (start = 1, end = 3)
- ‘d’ == ‘d’ (start = 2, end = 2)
- All characters match, so the method returns true.
Edge Cases
- Empty String:
- Input: “”
- Output: is palindrome string. (An empty string is considered a palindrome).
- Single Character String:
- Input: “A”
- Output: is palindrome string. (A single character is always a palindrome).
- String with Different Case:
- Input: “MadAm”
- Output: is palindrome string. (Case is ignored because the string is converted to lowercase).
- Non-Palindrome String:
- Input: “hello”
- Output: is not palindrome string. (The characters do not match from both ends).
Advantages
- Efficient: The solution compares characters from both ends and moves towards the center, reducing the number of comparisons needed.
- Case-Insensitive: The program handles case differences (i.e., ‘M’ and ‘m’ are treated equally).