Java program to check palindrome string using recursion

Let’s learn java program to check palindrome string using recursion.

Java program to check palindrome string using recursion

To check whether a string is palindrome or not using recursion is the most common java interview question.

Recursion means a function calling itself. In the below java program I have created ‘checkPalindrome()’ method with variable String ‘str’ as parameter.

checkPalindrome() method first checks if user entered string length is 0 or 1 using if statement. Here, if string length is equal to 0 or 1 then string is palindrome.

Also read – java program to reverse a string using recursion

If not, in the next if statement first and last character of string is checked.

If first and last character of string are same then carry out the same for substring with first and last character removed.

Also read – palindrome string program in java

This procedure is continued till condition fails. Let’s see sample java program to check if string is palindrome.

import java.util.Scanner;
public class RecursivePalindromeJava 
{
   // to check if string is palindrome using recursion
   public static boolean checkPalindrome(String str)
   {
      if(str.length() == 0 || str.length() == 1)
         return true; 
      if(str.charAt(0) == str.charAt(str.length() - 1))
         return checkPalindrome(str.substring(1, str.length() - 1));
      return false;
   }
   public static void main(String[]args)
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter a string : ");
      String strInput = sc.nextLine();
      if(checkPalindrome(strInput))
      {
         System.out.println(strInput + " is palindrome");
      }
      else
      {
         System.out.println(strInput + " not a palindrome");
      }
      sc.close();
   }
}


Output:

java program to check palindrome string using recursion

Also read – string palindrome in java using reverse method