palindrome is a string that reads the same both forward and

palindrome is a string that reads the same both forward and backward. For example, the string \"madam\" is a palindrome.

Write a program that uses a recursive function to check whether a string is a palindrome.

Your program must contain a value-returning recursive function that returns true if the string is a palindrome and false otherwise. Do not use any global variables; use the appropriate parameters.

Solution

StringPalindrome.java


public class StringPalindrome {

  
   public static void main(String[] args) {
       java.util.Scanner in = new java.util.Scanner(System.in);
       System.out.println(\"Please enter the string \");
       String str = in.nextLine();
       boolean status = isPalindrome(str);
       if(status){
           System.out.println(\"Given string is a palindrome\");
       }
       else{
           System.out.println(\"Given string is not a palindrome\");
       }
   }
   public static boolean isPalindrome(String str){
       // if length is 0 or 1 then String is palindrome
if(str.length() == 0 || str.length() == 1)
return true;
if(str.charAt(0) == str.charAt(str.length()-1))

return isPalindrome(str.substring(1, str.length()-1));
return false;
   }
}

Output:

Please enter the string
madam
Given string is a palindrome

Please enter the string
level
Given string is a palindrome

Please enter the string
abcd
Given string is not a palindrome

palindrome is a string that reads the same both forward and backward. For example, the string \

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site