Q:

Write a Java Program to Check String is Palindrome or not using Recursion

belongs to collection: Java String Solved Programs

0

Write a Java Program to Check String is Palindrome or not using Recursion. Here is our Java program, which checks if a given String is palindrome or not. Program is simple and here are steps to find palindrome String :

  • Reverse the given String
  • Check if reverse of String is equal to itself, if yes then given String is palindrome.

  • A String is nothing but a collection of characters e.g. “keyword” and String literals are encoded in double quotes in Java.
  • A String is said to be a palindrome if the reverse of String is equal to itself e.g. “mom” is a palindrome because the reverse of “mom” is also “mom”, but “java” is not a palindrome because the reverse of “java” is “avaj” which is not equal.
  • Recursion means solving a problem by writing a function which calls itself. In order to check if String is a palindrome in Java, we need a function which can reverse the String.
  • Once you have original and reversed String, all you need to do is check if they are equal to each other or not. If they are equal then String is palindrome or not. You can write this reverse() function by using either for loop or by using recursion.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

The following code accepts a string, and checks whether the given string is Palindrome or not using Recursion. The Program below is successfully compiled and run on the Windows System to produce desired output.

 
 

SOURCE CODE : :

import java.util.Scanner;

public class Palindrome_Recursion
{
   
    public static boolean isPal(String s)
    {   
        if(s.length() == 0 || s.length() == 1)
            return true; 
        
        if(s.charAt(0) == s.charAt(s.length()-1))
        return isPal(s.substring(1, s.length()-1));
        
       return false;
    }

    public static void main(String[]args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter any String for check String Palindrome : ");
        String string = sc.nextLine();
        if(isPal(string))
            System.out.println(string + " is a palindrome");
        else
            System.out.println(string + " is not a palindrome");
    }
}

OUTPUT : :

OUTPUT 1 :

        Enter any String for check String Palindrome : MADAM
        MADAM is a palindrome


OUTPUT 2 :

        Enter any String for check String Palindrome : codezclub
        codezclub is not a palindrome

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java String Solved Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java Program to find Lexicographically smallest an... >>
<< Write a Java Program to Check String is palindrome...