Search⌘ K

Solution Review: Is String a Palindrome?

Explore how to verify whether a string is a palindrome by writing and understanding a Java method that reverses a string using iteration. This lesson guides you through handling empty strings, traversing the string with a for loop, and comparing the reversed string to the original. You will gain practical skills in string manipulation and iteration concepts essential for mastering Java programming.

Rubric criteria

Solution

Java
class Palindrome
{
public static void main(String args[])
{
System.out.println( checkPalindrome("madam"));
}
public static boolean checkPalindrome(String str)
{
if (str.length() == 0)
{
return true;
}
else
{
String reversedString = "";
String currLetter;
for(int i=0; i < str.length(); i++)
{
currLetter = str.substring(i,i+1);
// add the letter at index i to what's already reversed.
reversedString = currLetter + reversedString;
}
if(str.equals(reversedString))
{
return true;
}
else
{
return false;
}
}
}
}

Rubric-wise explanation


Point 1:

Look at the header of the checkPalindrome() method at line 8. It’s a static function, and we call it without any need for an object. It takes the String parameter: str. First, we’ll handle the case of an empty string. If str is an empty string, we simply have to return true (see line 10). However, if str isn’t empty, we need to do the ...