Friday, September 15, 2023

How to check is given String is a 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 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;

/**
 * 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


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;

/**
 * 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 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.
  • How to reverse words in String in Java? (solution)
  • 10 Free Courses to learn Data Structure and Algorithms (courses)
  • How to find the highest occurring word from a text file in Java? (solution)
  • 100+ Data Structure and Algorithms Problems (solved)
  • 10 points about array in Java (read here)
  • 10 Books to learn Data Structure and Algorithms (books)
  • 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 a multi-dimensional array in Java (see here)
  • How to remove an element from an array without using a third-party library (check here)
  • How to find the largest and smallest number in an array in Java (read here)
  • Difference between array and ArrayList in Java (see here)
  • 10 Data Structure and Algorithms course to crack coding interview (courses)
  • How to find a missing number in a sorted array? (solution)
  • How to convert Array to String in Java (read here)
  • How to find two maximum numbers on an integer array in Java (check here)
  • How to loop over an array in Java (read here)

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 Educativative. 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. 

40 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
  3. package String;

    import java.util.Scanner;

    public class Palindrome {

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner sc= new Scanner(System.in);
    System.out.println("Enter your Palindrome String");

    String palindrome =sc.nextLine();
    int count=0;
    int countlength=palindrome.length()-1;

    for(int i=0;i<palindrome.length();i++)
    {
    if(palindrome.charAt(i)==palindrome.charAt(countlength))
    {
    count++;
    }
    countlength--;

    }
    if(count==palindrome.length())
    {
    System.out.println(" String is palindrome");
    }
    else
    {
    System.out.println(" Strin is not palindrome ");
    }

    }

    }

    ReplyDelete
  4. public boolean isPalindrome(String str) {
    int len = str.length();
    char[] chr = str.toCharArray();
    for(int i = 0; i<len/2; i++) {
    if(chr[i]!=chr[len-1-i]) {
    return false;
    }
    }
    return true;
    }

    ReplyDelete
  5. isPal(String word) {
    boolean isPal = false;
    int b_index = 0;
    int e_index = word.length()-1;
    while(b_index < e_index) {
    isPal = word.charAt(b_index) == word.charAt(e_index);
    b_index++;
    e_index--;
    }
    return isPal;
    }

    ReplyDelete
  6. private static Boolean palidromeString(String input, int length){
    if(input.length()%2==0){
    if(input.length()==0){
    return true;
    }
    if(input.charAt(length-1)==input.charAt(length-length)){
    return palidromeString(input.substring(input.length()-(input.length())+1,input.length()-1),
    input.substring(input.length()-(input.length())+1,input.length()-1).length());
    }
    }else {
    if(input.length()==1){
    return true;
    }
    return palidromeString(input.substring(input.length()-(input.length())+1,input.length()-1),input.substring(input.length()-(input.length())+1
    ,input.length()-1).length());
    }
    return false;
    }

    ReplyDelete







  7. class Ideone
    {
    static boolean isPalindrome(String str){
    String rev="";
    for(int i=str.length();i>=0;i--){
    rev+=str.charAt(i);


    }
    System.out.println(rev);
    if(str.equals(rev)){
    return true;
    }

    return false;
    }

    public static void main(String[] args){
    String str="madam";
    Ideone ii=new Ideone();
    ii.isPalindrome(str);
    }

    }

    Why it is giving the runtime error??

    ReplyDelete
    Replies
    1. Here
      for(int i=str.length();i>=0;i--)
      //it shoud be
      for(int i=str.length()-1;i>=0;i--)

      Delete
  8. private static boolean isPalindrome(String s)
    {
    return s.equals(new StringBuilder(s).reverse().toString());
    }

    ReplyDelete
    Replies
    1. Hello Anonymous, you need to solve this problem with your own logic without using reverse() method from Java framework.

      Delete
  9. public static boolean isPalindrome(String input) {
    if(input == null || input.length() < 2) {
    return true;
    }
    for(int i = 0, j = input.length() - 1; i < j; i++, j--) {
    if(input.charAt(i) != input.charAt(j)) {
    return false;
    }
    }
    return true;
    }

    ReplyDelete
    Replies
    1. good one. but 'input.length() < 2' should be 'input.length() <= 2' otherwise it goes inside the loop even for a 2 letter word like 'aa' which is not a palindrome.

      Delete
  10. one liner in python:

    def checkPalindrom(input):
    return input == input[::-1]

    ReplyDelete
  11. one line in python

    input == input[::-1]

    ReplyDelete
  12. please don't teach anyone to reverse strings using recursion, or worse, check if they are a palindrome by reversing and comparing the string, if an interviewer asks me to do this i will tell him its a bad idea, this is ONLY useful for interviews, a sane programmer would never do this.

    ReplyDelete
    Replies
    1. How would a sane programmer write a function for checking a palindrome?

      Delete
    2. like this i would guess
      StringBuffer str = new StringBuffer(word);
      str = str.reverse();
      if (str.toString().equals(word)) {
      return true;
      } else {
      return false;
      }

      Delete
    3. here the catch is to check the logic (time complexity). A 'sane' programmer would stop comparing the at half way (length-1 / 2). If the interviewer compares the whole string, he/she is not good.

      Delete
    4. Be sure to determine if you need to keep char case or not. Racecar vs racecar.

      public static bool IsPalindrome(string text)
      {
      for(var i = 0; i < text.Length / 2; i++)
      {
      if(Char.ToLower(text[i]) != Char.ToLower(text[(text.Length - 1) - i]))
      {
      return false;
      }
      }

      return true;
      }

      Delete
  13. Boolean isTrue = true;

    for(int i=0,j=data.length()-1; i=0;i++,j--){
    String a1, a2;
    a1 = String.valueOf(data.charAt(i));
    a2 = String.valueOf(data.charAt(j));
    if(!a1.equals(a2)){
    isTrue = false;
    break;
    }
    }

    if(isTrue){
    Log.e("TAG-PALENDROME", "TRUE");
    }else {
    Log.e("TAG-PALENDROME", "FALSE");
    }

    ReplyDelete
  14. Hi team,
    i'm very bad in codding so i want to know the internal flow of the below code.
    how and where it appends the value and pass the reverse string to its function.

    return input.charAt(input.length()- 1) + reverse(input.substring(0, input.length() - 1));

    ReplyDelete
    Replies
    1. Hello xyz, this is recursion which is best explained as an example, support you need to reverse the string "ANY" you past this to method and then it will expand as below

      input.charAt(input.length()- 1) will return "Y" + reverse ("AN")

      in next round it will be "Y" + "N" + reverse ("A")

      and this time reverse will return "A" and you will have output as "YNA"

      Delete
    2. how
      reverse(input.substring(0, input.length() - 1))
      giving it's last value to input.charAt(input.length()- 1) as
      reverse(input.substring(0, input.length() - 1)) calling it's on method every time and pass the string between (0 and input.length() - 1)

      Delete
  15. Solution in javascript:

    function palindrome(str) {
    if(str.length > 0) {
    var middle = parseInt(str.length/2);
    for(var i = 0, j = str.length -1; i <= middle; i++) {
    if(str[i] === str[j]) {
    j--;
    } else {
    return false
    }
    }
    } else {
    return false
    }
    return true
    }

    palindrome("abc") // false
    palindrome("dededed") // true

    ReplyDelete
  16. public static boolean isStringPalindrome(String stringToCheck) {
    StringBuilder stringBuilder = new StringBuilder();
    String reversedString = stringBuilder.append(stringToCheck).reverse().toString();
    return stringToCheck.equals(reversedString);
    }

    ReplyDelete
    Replies
    1. Nice and easy but can you solve this problem without using StringBuilder.reverse() method? That's most likely will be asked during interview

      Delete
  17. package com.Test;

    import java.util.Scanner;

    public class Main{
    public static void main(String[] args){
    String a,b="";
    Scanner scanner = new Scanner(System.in);
    a=scanner.nextLine();
    int n= a.length();
    for(int i=n-1; i>=0;i--){
    b=b+a.charAt(i);
    }
    if(a.equalsIgnoreCase(b)){
    System.out.println("palindrome");
    }
    else{
    System.out.println("not palindrome");
    }
    }
    }

    ReplyDelete
  18. Another simpler solution
    public class HelloWorld{

    public static void main(String args[]) {


    System.out.println("Hello world "+ isPalandrome());

    }


    public static boolean isPalandrome(){
    String name = "anbbna";
    char[] array = name.toCharArray();

    int length_ = name.length();

    for(int i = 0 ; i < length_ /2;i++ ){

    if(array[i] != array[length_-1-i]){
    return false;
    }
    }

    return true;
    }
    }


    ReplyDelete
  19. int l=s.length()-1;
    int i=0, j=l;
    boolean flag=true;
    while(i<j)
    {
    if(s.charAt(i) != s.charAt(j))
    {
    flag= false;
    }
    i++;j--;
    }
    if(!flag)
    {
    System.out.println("Not palindrome");
    }
    else{
    System.out.println("palindrome");
    }

    ReplyDelete
  20. String test = "123321";
    System.out.println(test.equals(new StringBuilder(test).reverse().toString()));

    Simple and one step.

    ReplyDelete
  21. // Online Java Compiler
    // Use this editor to write, compile and run your Java code online

    class HelloWorld {
    public static void main(String[] args) {
    String str= "bbbbb";
    char ch[]= str.toCharArray();
    if(Palindrome(ch))
    System.out.println("palindrome");
    else System.out.println("NOT palindrome");
    }

    static boolean Palindrome(char ch[]){
    int i=0;
    int j= ch.length-1;

    if(ch.length%2 != 0) return false;
    while(i<j){
    if(ch[i]!=ch[j])
    return false;

    else i++; j--;

    }
    return true;
    }
    }

    ReplyDelete
  22. public boolean checkStringPalindrome(String word){

    StringBuilder newWord = new StringBuilder(word);
    String reverseWord = newWord.reverse().toString();
    if(reverseWord.equalsIgnoreCase(word))
    return true;
    return false;
    }

    ReplyDelete
  23. private static boolean isItPalindrome(String inputString)
    {
    //Clean inpuString by removing spaces and negating the case of the letters

    String cleanInputString = inputString.replaceAll("\\s+", "").toLowerCase();

    //Convert cleanInputString to char array

    char[] charArray = cleanInputString.toCharArray();

    //Let forward index point at first character

    int forward = 0;

    //And backward index point at last character

    int backward = charArray.length - 1;

    //start iterating charArray from both ends simultaneously

    while (forward <= backward)
    {
    if(charArray[forward] != charArray[backward])
    {
    //If chars at both ends are not same, return false

    return false;
    }

    //If chars at both ends are same, increment forward and decrement backward

    forward++;

    backward--;
    }

    return true;
    }

    ReplyDelete
  24. private static boolean palendromeString(String str) {

    boolean palentrome =false;
    if(null == str || "".equalsIgnoreCase(str))
    return palentrome;

    //char[] stringArray = str.toCharArray();

    for(int i=1;i<=str.length()-1;i++) {

    if(str.charAt(i)==str.charAt(str.length()-1-i)) {
    palentrome = true;

    }else {
    palentrome=false;
    break;
    }


    }

    return palentrome;
    }

    ReplyDelete
  25. we can use this

    ReplyDelete
    Replies
    1. Thanks for helping others Kishore, appreciate it.

      Delete
  26. private static boolean isPalindrome(String input) {
    String check= Arrays.stream(input.split(" ")).map(word -> new StringBuilder(word).reverse()).collect(Collectors.joining(" "));
    if (input.equals(reverse) && !input.isEmpty() && !input.isBlank()) {
    return true;
    } else {
    return false;
    }
    }
    }

    ReplyDelete
  27. in -> if() replace (reverse) with check

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.