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

By | 12.03.2017

Java Program to Check String is Palindrome or not using Recursion


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.

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
0 0 votes
Article Rating
Category: Java Programming String Programs Tags:

About Tunde A

My name is Tunde Ajetomobi, a Tech Enthusiast and Growth Hacker. I enjoy creating helpful content that solves problem across different topics. Codezclub is my way of helping young aspiring programmers and students to hone their skills and find solutions on fundamental programming languages.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments