In: Computer Science
Write a recursive method to determine if a String is a palindrome. Create a String array with several test cases and test your method.
Write a recursive method to determine if a String is a palindrome. Create a String array with several test cases and test your method. In Java
Code:
import java.util.*;
class Main {
      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 our string completes or condition fails
           */
          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) {
        //String array with test cases
        String[] arr = {"hello","racecar","malyalam","nothing"};
        for(int i = 0;i<arr.length;++i){
            if(isPalindrome(arr[i])){
                System.out.println(arr[i] + " is palindrome");
            }else{
                System.out.println(arr[i] + " is not palindrome");
            }
        }
    }
}
output:

code screenshot:
