$show=/label

Java Program to check String is Palindrome Or Not (Best way and Recursive)

SHARE:

1. Introduction In this article, We will be learning how to write a java program to check whether a given string is a palindrome or not....

1. Introduction


In this article, We will be learning how to write a java program to check whether a given string is a palindrome or not. This can be solved in many ways and will see all possible ways.

First, What is a palindrome? A String is said palindrome if and only if all characters of the string remain the same even the string is reversed. To solve this first we need to reverse the string and compare the reversed string with the original string. If both are same then the given string is a palindrome, Otherwise, it is not.

java-program-check-string-palindrome


Example:

String input = "madam";
String reversedString = "madam";

Let us observe that input and reversedString contents are the same. So, the input string is called a palindrome.


String input2 = "hello";
String reversedString2 = "olleh";

input2 and reversedString2 contents are not the same so input2 "hello" is not a palindrome.

In previous tutorials, we have shown the java program to find all palindromes for a given range. Read more here.

As we stated earlier this can be solved by using java built-in API methods or use the core logic to check or determine string is a palindrome.

.
A) Using built-in reverse() method
B) Using StringBuffer class
C) Using additional String
D) Without using any library method or additional Strings.
F) Recursive approach
.

2) String Palindrome Program: Using the built-in reverse() method of StringBuffer


StringBuffer API has a reverse() method which does the job for us to reverse the contents. reverse() method returns the StringBuffer so we need to convert it to String by invoking the toString() method. toString() is to convert the StringBuffer to String.

package com.javaprogramto.engineering.programs;

public class StringPalindromeReverse {

    public static void main(String[] args) {
        String input1 = "madam";
        String reversedString1 = reverseString(input1);

        if (input1.equals(reversedString1)) {
            System.out.println(input1 + " is a palindrome");
        } else {
            System.out.println(input1 + " is not a palindrome");
        }

        String input2 = "hello";
        String reversedString2 = reverseString(input2);

        if (input2.equals(reversedString2)) {
            System.out.println(input2 + " is a palindrome");
        } else {
            System.out.println(input2 + " is not a palindrome");
        }

    }

    private static String reverseString(String input) {

        StringBuffer buffer = new StringBuffer();
        buffer.append(input);

        return buffer.reverse().toString();
    }

}

Output:

madam is a palindrome
hello is not a palindrome

3) String Palindrome Program: Using StringBuffer class append() method


We run the for loop from index length-1 to 0. That means retrieving each character from the last index to the first index and then add it to StringBuffer. After adding all characters of string to StringBuffer Finally covert StringBuffer to String using toString() method.

Read more on for loop.

package com.javaprogramto.engineering.programs;

public class StringPalindromeAppend {

    public static void main(String[] args) {
        String input1 = "civic";
        String reversedString1 = reverseString(input1);

        if (input1.equals(reversedString1)) {
            System.out.println(input1 + " is a palindrome");
        } else {
            System.out.println(input1 + " is not a palindrome");
        }

        String input2 = "civics";
        String reversedString2 = reverseString(input2);

        if (input2.equals(reversedString2)) {
            System.out.println(input2 + " is a palindrome");
        } else {
            System.out.println(input2 + " is not a palindrome");
        }

    }

    private static String reverseString(String input) {

        StringBuffer buffer = new StringBuffer();

        for (int i = input.length() - 1; i >= 0; i--) {
            buffer.append(input.charAt(i));
        }
        return buffer.toString();
    }

}

Output:

civic is a palindrome
civics is not a palindrome

4. String Palindrome Program: Using a new String variable


As in the above, we use String instead of StringBuffer and add all characters to a new String object. See the below program.

package com.javaprogramto.engineering.programs;

public class StringPalindromeAdditionalString {

    public static void main(String[] args) {
        String input1 = "radar";
        String reversedString1 = reverseString(input1);
        if (input1.equals(reversedString1)) {
            System.out.println(input1 + " is a palindrome");
        } else {
            System.out.println(input1 + " is not a palindrome");
        }

        String input2 = "radars";
        String reversedString2 = reverseString(input2);

        if (input2.equals(reversedString2)) {
            System.out.println(input2 + " is a palindrome");
        } else {
            System.out.println(input2 + " is not a palindrome");
        }

    }

    private static String reverseString(String input) {

        String output = "";

        for (int i = input.length() - 1; i >= 0; i--) {
            output = output + input.charAt(i);
        }
        return output;
    }

}

Output:

radar is a palindrome
radar1 is not a palindrome

In the above three approaches, the problem is consuming the additional memory using StringBuffer or additional String instance.

5. String Palindrome Program: Recursive approach


Here logic to compare the first index value and last index value and then next first index -1 and last index -1.. like this compare till the start index becomes a mid-index. If anyone of these comparison fails then it is not a palindrome. If all comparisons are equal then it is a palindrome.

You need to observe that not used any additional memory and no library methods apart from charAt(). This solution is quite precise and used logic. This the answer that the interviewer expects if you are an experienced developer.

package com.javaprogramto.engineering.programs;

public class StringPalindromeWithoutLibraryHelp {

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

        String input2 = "levels";
        boolean isPal2 = isPalindrome(input2);

        if (isPal2) {
            System.out.println(input2 + " is a palindrome");
        } else {
            System.out.println(input2 + " is not a palindrome");
        }

    }

    private static boolean isPalindrome(String input) {

        int length = input.length();
        for (int start = 0, end = length - 1; start <= length / 2; start++, end--) {

            if (input.charAt(start) != input.charAt(end)) {
                return false;
            }
        }
        return true;
    }

}

Output:

level is a palindrome
levels is not a palindrome

6. String Palindrome Program: Recursive approach


The below-shown program is implemented using a recursive approach. Read the comments in isPalindrome() method will give a clear understanding of each line of code.
Comparatively, this way uses two methods charAt() and substring() methods.

Recursive program to print the Fibonacci series and find the nth Fibonacci number.


package com.javaprogramto.engineering.programs;

public class StringPalindromeRecursive {

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

        String input2 = "rac ecar";
        boolean isPal2 = isPalindrome(input2);

        if (isPal2) {
            System.out.println(input2 + " is a palindrome");
        } else {
            System.out.println(input2 + " is not a palindrome");
        }

    }

    private static boolean isPalindrome(String input) {

        // this is the end of recursive. If length is 0 or 1 then stopping the process.
        if (input.length() == 0 || input.length() == 1)
            return true;

        // comparing the first and last index values.
        if (input.charAt(0) == input.charAt(input.length() - 1))

            // calling again isPalindrome() method but we are not passing the complete
            // string. Passing the remaining string after removing the first and last index.
            // For each recursive call, we will be removing the compared characters using
            // substring() method of string class.
            return isPalindrome(input.substring(1, input.length() - 1));

        return false;
    }

}

Output:

racecar is a palindrome
rac ecar is not a palindrome

7. Conclusion


In this article, you have seen all possible ways to find a given string is a palindrome or not. But the effective way is not using any built-in API classes and reverse() method. Comparing the first and last character approach is the best one (i.e. section 5). The recursive approach is also good but it has multiple calls to string API methods. Otherwise, the recursive approach has to be considered.

You reached this point means you liked the article, please share with your friends on facebook or WhatsApp using below share options.

COMMENTS

BLOGGER: 1
  1. This comment has been removed by a blog administrator.

    ReplyDelete
Please do not add any spam links in the comments section.

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java Program to check String is Palindrome Or Not (Best way and Recursive)
Java Program to check String is Palindrome Or Not (Best way and Recursive)
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWVWU7QfKgEbA-oMwGpyuTL4QpQX-KaYF6_Gf5fkBW1ai-0xAOXv1UOB-onCUNnZe3-USjyi3E4hS935EzLJoT6O5JPXeFxHf_NloO9uZf4GDK9GfcSZ6xXraXTqi-1CWck7RRaCp2Cu0/s400/java-program-check-string-palindrome.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWVWU7QfKgEbA-oMwGpyuTL4QpQX-KaYF6_Gf5fkBW1ai-0xAOXv1UOB-onCUNnZe3-USjyi3E4hS935EzLJoT6O5JPXeFxHf_NloO9uZf4GDK9GfcSZ6xXraXTqi-1CWck7RRaCp2Cu0/s72-c/java-program-check-string-palindrome.png
JavaProgramTo.com
https://www.javaprogramto.com/2019/11/java-program-check-string-palindrome.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/11/java-program-check-string-palindrome.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content