Flash cards
Review the key moves
What is the main idea behind Java How To - Palindrome Check?
Lesson checks
Practice each idea before moving on
Short Mimo-style checks built from this lesson's code, terms, and sequence.
Which statement best captures the main point of this lesson?
Complete the missing token from the example code.
___ text = "level";Put the learning moves in the order that makes the concept easiest to apply.
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 Since all characters match, the word is a palindrome.
- 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.