Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The usual denition of a palindrome is a word that reads the same both forward an

ID: 3677173 • Letter: T

Question

The usual denition of a palindrome is a word that reads the same both forward and backward, like “otto” and “palindromeemordnilap.” An alternative way to dene a property like this is to specify a way of testing for the property. For example, we might say, “a single letter is a palindrome, and a two-letter word is a palindrome if the letters are the same, and any other word is a palindrome if the rst letter is the same as the last and the middle is a palindrome.”

Write a recursive method( JAVA PROGRAM) named isPalindrome that takes a String and that returns a boolean indicating whether the word is a palindrome or not.

Explanation / Answer

import java.util.Scanner;
class PalindromeCheck
{
//My Method to check
public static boolean isPalindrome(String s)
{ // if length is 0 or 1 then String is palindrome
if(s.length() == 0 || s.length() == 1)
return true;
if(s.charAt(0) == s.charAt(s.length()-1))
/* check for first and last char of String:
* if they are same then do the same thing for a substring
* with first and last char removed. and carry on this
* until you string completes or condition fails
* Function calling itself: Recursion
*/
return isPalindrome(s.substring(1, s.length()-1));

/* If program control reaches to this statement it means
* the String is not palindrome hence return false.
*/
return false;
}

public static void main(String[]args)
{
   //For capturing user input
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the String for check:");
String string = scanner.nextLine();
/* If function returns true then the string is
* palindrome else not
*/
if(isPalindrome(string))
System.out.println(string + " is a palindrome");
else
System.out.println(string + " is not a palindrome");
}
}