How to check is given String is a Palindrome in Java using Recursion (original) (raw)

In this tutorial, you will learn how to check if a string is a palindrome in Java using Recursion. A String is nothing but a collection of characters like "Java," 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 like "aba" is a palindrome because the opposite of "aba" is also "aba", but "abc" is not a palindrome because the reverse of "abc" is "cba" 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 that can reverse the String.

Once you have the 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.

If you remember, I already shared the logic of reversing String in my earlier post, how to reverse String in Java using Iteration and Recursion. Here we will use the same logic to check if String is palindrome or not.

By the way, if you are preparing for coding interviews and looking for some coding problem to get hands-on practice, I suggest you take a look at Data Structures and Algorithms: Deep Dive Using Java by Tim Buchalaka and his team on Udemy.

This is a beautiful course, which contains lots of natural and medium difficulty level coding problems, which will not only help you to prepare for an interview but also develop your programming logic and Data Structure, and Algorithms skills. It's also very affordable and you can buy in just $10 on many Udemy sales which happen every now and then.

Java Program to check if String is Palindrome Using Recursion

Here is our Java program, which checks if a given String is palindrome or not. The program is simple, and here are steps to find palindrome String :

  1. Reverse the given String
  2. Check if the reverse of String is equal to itself; if yes, then given String is a palindrome.

In our solution, we have a static method isPalindromeString(String text), which accepts a String. It then calls the reverse(String text) method to reverse this String.

This method uses Recursion to reverse String. This function first checks if the given String is null or empty, if yes then it returns the same String because they don't require to be reversed.

After this validation, it extracts the last character of String and passes rest or String using substring() method to this method itself, hence the recursive solution.

The validation also servers as base case because, after every step, String keeps getting reduced, and eventually it will become empty, there your function will stop Recursion and will use String concatenation to concatenate all character in reverse order. Finally, this method returns the reverse of String.

When the call to reverse() returns back, isPalindromeString(String text) uses the equals() method to check if the reverse of String is equal to the original String or not, if yes then it returns true, which also means String is a palindrome.

As I said if you are looking for more coding-based problems you can also always check the Grokking the Coding Interview: Patterns for Coding Questions course on Educative, one of the great courses to build coding sense and pattern recognition required to clear programming interviews.

How to check if String is palindrome in Java using recursion

How to check if String is Palindrome in Java using Recursion

Here is the complete Java program to check if the given String is palindrome or not. In this program, we have used Recursion to first reverse the String and then check if both original and reversed String is the same or not.

package test;

/**

}

Output Is aaa palindrom?: true Is abc palindrom?: false Is bbbb palindrom?: true Is defg palindrom?: false

And, if you are looking for more coding-based problems you can also always check the Cracking the Coding Interview: 150 Programming Questions and Solutions, one of the great books to build the coding sense required to clear programming interviews.

How to find if a String is Palindrome in Java

How to check if String is Palindrome using StringBuffer and For loop

You can also solve this problem by retrieving the character array from String using the toCharArray() and using a for loop and StringBuffer. All you need to do is iterate through the character array from end to start i.e. from the last index to the first index and append those characters into the StringBuffer object.

Once this is done, just call the toString() method of StringBuffer, it's your reversed String.

Here is how your code will look like :

import java.util.Scanner;

/**

public class Palindrome{

public static void main(String args[]) {
   
    Scanner reader = new Scanner(System.in);
    System.out.println("Please enter a String");
    String input = reader.nextLine();
    
    System.out.printf("Is %s a palindrome? : %b %n", 
                          input, isPalindrome(input));
    
    
    System.out.println("Please enter another String");
    input = reader.nextLine();
    
    System.out.printf("Is %s a palindrome? : %b %n", 
                          input, isPalindrome(input));
    
    reader.close();
    

}

public static boolean isPalindrome(String input) {
    if (input == null || input.isEmpty()) {
        return true;
    }

    char[] array = input.toCharArray();
    StringBuilder sb = new StringBuilder(input.length());
    for (int i = input.length() - 1; i >= 0; i--) {
        sb.append(array[i]);
    }

    String reverseOfString = sb.toString();

    return input.equals(reverseOfString);
}

}

That's all about how to check for palindrome in Java. You have learned how to find if a given String is palindrome using Recursion as well by using StringBuffer and for a loop. More importantly, you have done it by developing your own logic and writing your own code i.e. not taking help from a third-party library.

If you want to do, you can write some unit tests for our recursive and iterative palindrome functions and see if it works in all conditions including corner cases.

If you like this coding problem and are interested to do more coding exercises, you can also check the following beginner-level programming exercises.

This will help to develop your programming logic and how to use basic tools of a programming language like operators, loop, conditional statements, data structure, and core library functions.

Thanks for reading this article so far. If you find this coding problem interesting and my explanation useful then please share it with your friends on Facebook and LinkedIn. If you have any questions or feedback then please drop a note.

P. S. - If you are preparing for a programming job interview, then you must prepare for an all-important topic like data structure, String, array, etc. One book which can help you with this task is the Grokking the Coding Interview: Patterns for Coding Questions course on Educative. It contains popular coding interview patterns which will help you to solve most of the problems in your coding interviews.

By the way, What is your favorite Java coding exercise? Fibonacci series, Prime Number, Producer consumer problem , or this one? Do let me know in comments.