w3resource

Java Recursive Method: String palindrome detection

Java Recursive: Exercise-4 with Solution

Write a Java recursive method to check if a given string is a palindrome.

Sample Solution:

Java Code:

public class PalindromeChecker {

  public static boolean isPalindrome(String str) {
    // Base case: an empty string or a string with one character is a palindrome
    if (str.length() <= 1) {
      return true;
    }

    // Recursive case: check if the first and last characters are equal,
    // and recursively check if the substring between them is a palindrome
    char firstChar = str.charAt(0);
    char lastChar = str.charAt(str.length() - 1);

    if (firstChar != lastChar) {
      return false;
    }

    String remainingSubstring = str.substring(1, str.length() - 1);
    return isPalindrome(remainingSubstring);
  }

  public static void main(String[] args) {
    String palindrome1 = "madam";
    boolean isPalindrome1 = isPalindrome(palindrome1);
    System.out.println(palindrome1 + " is a palindrome: " + isPalindrome1);

    String palindrome2 = "level";
    boolean isPalindrome2 = isPalindrome(palindrome2);
    System.out.println(palindrome2 + " is a palindrome: " + isPalindrome2);

    String notPalindrome = "java";
    boolean isPalindrome3 = isPalindrome(notPalindrome);
    System.out.println(notPalindrome + " is a palindrome: " + isPalindrome3);
  }
}

Sample Output:

madam is a palindrome: true
level is a palindrome: true
java is a palindrome: false

Explanation:

In the above exercises -

We define a class "PalindromeChecker" that includes a recursive method isPalindrome() to check if a given string str is a palindrome.

The isPalindrome() method has two cases:

  • Base case: If the string length is 0 or 1, it returns true because an empty string or a string with one character is considered a palindrome.
  • Recursive case: It compares the first and last characters of the string. If they are not equal, it returns false. Otherwise, it extracts the remaining substring between the first and last characters, and recursively checks if this substring is a palindrome. This process continues until the string is reduced to an empty string or one character.

In the main() method, we demonstrate the isPalindrome() method by checking if different strings are palindromes and printing the results.

Flowchart:

Flowchart: Java  recursive Exercises: String palindrome detection.

Java Code Editor:

Java Recursive Previous: Calculate the nth Fibonacci number.
Java Recursive Next: Calculate Base to Power.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-exercises/recursive/java-recursive-exercise-4.php