Java How To - Palindrome Check
How To Check if a String Is a Palindrome
Learn how to check whether a word reads the same forward and backward (like "level"
):
Example
String text = "level";
boolean isPalindrome = true;
for (int i = 0; i < text.length() / 2; i++) {
if (text.charAt(i) != text.charAt(text.length() - 1 - i)) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
System.out.println(text + " is a palindrome");
} else {
System.out.println(text + " is not a palindrome");
}
Explanation:
We compare the first character with the last, the second with the second-last, and so on.
- If all pairs match, the string is a palindrome.
- If any pair does not match, it is not a palindrome.
For example, in "level"
:
l == l
e == e
Using StringBuilder
You can also use StringBuilder
, which is a special Java class that makes it easy to work with and change strings (for example, reversing them):
Example:
String text = "level";
String reversed = new StringBuilder(text).reverse().toString();
if (text.equalsIgnoreCase(reversed)) {
System.out.println(text + " is a palindrome");
} else {
System.out.println(text + " is not a palindrome");
}
Explanation:
We take the string text
and use StringBuilder.reverse()
to create its reverse.
If the original and reversed strings are the same (ignoring case with equalsIgnoreCase()
), then it is a palindrome.