How to Check is a String is Palindrome in Java using Recursion

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 e.g. "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 e.g. "aba" is a palindrome because the reverse 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 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.

If you remember, I already shared 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 to take a look at Cracking the Coding Interview: 150 Programming Questions and Solutions. This is a wonderful book, which contains lots of easy and medium difficulty level coding problems, which will not only help you to prepare for interview but also develop your programming logic.





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. Program is simple and here are steps to find palindrome String :

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

In our solution, we have a static method isPalindromeString(String text), which accepts a String. It then call reverse(String text) method to reverse this String. This method uses recursion to reverse String. This function first check if given String is null or empty, if yes then it return the same String because they don't require to be reversed.

After this validation, it extract last character of String and pass rest or String using substring() method to this method itself, hence 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.

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

As I said, 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 book to build coding sense required to clear programming interviews.

How to find if a String is Palindrome in Java



How to check if String is Palindrome in Java using Recursion


package test;

/**
 * Java program to show you how to check if a String is palindrome or not.
 * An String is said to be palindrome if it is equal to itself after reversing.
 * In this program, you will learn how to check if a string is a palindrome in java using recursion
 * and for loop both. 
 *
 * @author Javin
 */
public class PalindromeTest {

   
    public static void main(String args[]) {
        System.out.println("Is aaa palindrom?: " + isPalindromString("aaa"));
        System.out.println("Is abc palindrom?: " + isPalindromString("abc"));
       
        System.out.println("Is bbbb palindrom?: " + isPalindromString("bbbb"));
        System.out.println("Is defg palindrom?: " + isPalindromString("defg"));
     
       
    }

    /**
     * Java method to check if given String is Palindrome
     * @param text
     * @return true if text is palindrome, otherwise false
     */
    public static boolean isPalindromString(String text){
       String reverse = reverse(text);
       if(text.equals(reverse)){
           return true;
       }
     
       return false;
    }
   
    /**
     * Java method to reverse String using recursion
     * @param input
     * @return reversed String of input
     */
    public static String reverse(String input){
        if(input == null || input.isEmpty()){
            return input;
        }
       
        return input.charAt(input.length()- 1) + reverse(input.substring(0, input.length() - 1));
    }
   
}

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


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

How to check if String is palindrome in Java using recursion


Once this is done, just call the toString() method of StringBuffer, its your reversed String. Here is how your code will look like :

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

import java.util.Scanner;

/**
 * How to check if String is palindrome in Java 
 * using StringBuffer and for loop.
 * 
 * @author java67
 */

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 loop. More importantly you have done it by developing your own logic and writing your own code i.e. not taking help from third party library. If you want to do, you can write some unit test 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 interested to do more coding exercises, you can also check following beginner level programming exercises. This will help to develop your programming logic and how to use basic tools of a programming language e.g. operators, loop, conditional statements, data structure and core library functions.
  • How to reverse words in String in Java? (solution)
  • 10 points about array in Java (read here)
  • 4 ways to sort array in Java (see here)
  • How to print array in Java with examples (read here)
  • How to compare two arrays in Java (check here)
  • How to declare and initialize multi-dimensional array in Java (see here)
  • How to remove element from array without using third party library (check here)
  • How to find largest and smallest number in an array in Java (read here)
  • Difference between array and ArrayList in Java (see here)
  • How to convert Array to String in Java (read here)
  • How to find two maximum number on integer array in Java (check here)
  • How to loop over array in Java (read here)

Recommended books for coding problems and practice
  • Cracking the Coding Interview: 150 Programming Questions and Solutions (check here)
  • Coding Puzzles: Thinking in code By codingtmd (check here)
  • Programming Interviews Exposed: Secrets to Landing Your Next Job (check here)

2 comments:

  1. public static boolean isPalindromString(String input) {
    for (int i = 0; i < input.length() / 2; i++)
    if (input.charAt(i) != input.charAt(input.length() - i - 1))
    return false;
    return true;
    }

    ReplyDelete
  2. private static void palindrome(String string) {
    char[] ch = string.toCharArray();
    int count =0;
    for(int i=0; i< ch.length/2; i++) {
    if(ch[i] == ch[ ch.length-1-i]){

    count++;
    continue;

    }else{
    count =0;
    System.out.println("not palindrome");
    }
    }

    if(count >0) {
    System.out.println(" palindrome");
    }

    }

    ReplyDelete