Google News
logo
Java Program to check Palindrome string using Recursion
In the following example of Java program to check if a string is a palindrome using recursion :
Program :
public class Palindrome {

    public static void main(String[] args) {
        String str = "racecar";
        if (isPalindrome(str)) {
            System.out.println(str + " is a palindrome.");
        } else {
            System.out.println(str + " is not a palindrome.");
        }
    }

    public static boolean isPalindrome(String str) {
        if (str.length() <= 1) {
            return true;
        } else {
            char first = str.charAt(0);
            char last = str.charAt(str.length() - 1);
            if (first == last) {
                return isPalindrome(str.substring(1, str.length() - 1));
            } else {
                return false;
            }
        }
    }
}
Output :
racecar is a palindrome.
* In this program, we first declare a string variable str and initialize it with the value "racecar". We then call the isPalindrome method, passing in str, and print the appropriate message depending on whether the method returns true or false.

* The isPalindrome method is defined as a static method that takes a string parameter str and returns a boolean. The method uses recursion to check if the string is a palindrome.

* If the length of the string is less than or equal to 1, it simply returns true. Otherwise, it compares the first and last characters of the string. If they are equal, it recursively calls itself with the substring of the original string starting from index 1 and ending at the second to last index, effectively removing the first and last characters from the string. If they are not equal, it returns false.