Java Program to check palindrome using recursion


March 27, 2022, Learn eTutorial
1837

What is a palindrome?

Palindrome means a name, number, or string that reads the same when we read from backward and forward.

Example: madam, level, mom, noon

Here we are explaining how to write a java program to check whether a string is a palindrome or not using a recursive function.

What is a palindrome

How to implement the java program to check whether a string is a palindrome or not by using recursion?

First, we have to declare the class Palindrome. Then we have to read a string from the user into the variable str. By using an if condition calls the function isPalindrome(str). If it returns a true value then we will display the string as a palindrome, otherwise, we will display the string is not a palindrome.

The function check if s.length()=0 or s.length()=1,if true then the function return true.Else it will check the first character of the string and the last character of the string are equal or not. If equal then we will check the next character with the second last character and so on until the string length becomes 1 or zero. If the string is not palindrome the function returns false.

ALGORITHM

STEP 1: Declare the class Palindrome with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3: Declare the string variable str.

STEP 4: Read the string from the user into the variable str.

STEP 5: By using if condition check isPalindrome (str) is true or false.If true then display the string as a palindrome. Else display the string is not a palindrome.

 

FUNCTION static boolean isPalindrome(String s)

STEP 1:Check if s.length()==0 or s.length()==1,then return true.

STEP 2: Else check the first character and the last character of the string are equal or not,if equal then return isPalindrome(s.substring(1, s.length()-1));

STEP 3: Return false.

Java Source Code

                                          import java.util.Scanner;
public class Palindrome {
 public static void main(String[] args) {
  Scanner sc = new Scanner(System. in );
  System.out.println("Enter the String:");
  String str = sc.nextLine();
  if (isPalindrome(str)) System.out.println(str + " is a palindrome string");
  else System.out.println(str + " is not a palindrome string");
 }
 public static boolean isPalindrome(String s) {
  if (s.length() == 0 || s.length() == 1) return true;
  if (s.charAt(0) == s.charAt(s.length() - 1))

  return isPalindrome(s.substring(1, s.length() - 1));

  return false;
 }

}
                                      

OUTPUT

Enter the String:
madam
madam is a palindrome string