Best Palindrome Program in Java of 2021

Palindrome Program in Java

1. Problem Introduction

As the post name suggest “Palindrome Program in Java” we will be going to check how we can get the string as palindrome in Java, There are multiple ways to achieve this. In this Post, we will be going to see how we can get and check whether a given input String is a palindrome using Palindrome Program in Java.

A palindrome is a word, string, phrase, number, or other sequences of characters and numbers which reads the same from both ends, such as “madam” or “RadaR” o “12321”

2. Solution to Palindrome Problem

Here in the following post , we have proposed various solutions and we will be going to check how we can achieve and check if String is a palindrome or not. There are two approaches to check Palindrome Program in Java , here are the below.

2.1. A Simple Approach

We can simultaneously start iterating the given string forward and backward, one character at a time to find Palindrome Program in Java. If the there is a match the loop continues; otherwise, the loop exits:

public boolean isPalindrome(String text) {
    String clean = text.replaceAll("\\s+", "").toLowerCase();
    int length = clean.length();
    int forward = 0;
    int backward = length - 1;
    while (backward > forward) {
        char forwardChar = clean.charAt(forward++);
        char backwardChar = clean.charAt(backward--);
        if (forwardChar != backwardChar)
            return false;
    }
    return true;
}

Palindrome Program in java: A palindrome number is a number that is same after reverse. For example 242, 121, 2345432, 13431, 1117111, 664898466 are the palindrome numbers. It can also be a string like LOL, RADAR, MADAM etc.

The simple approach is to check Palindrome Program in Java is to have each substring whether the substring is a palindrome or not. To do this first, run three nested loops, the outer two loops pick all substrings one by one by fixing the corner characters, the inner loop checks whether the picked substring is palindrome or not. 

Palindrome number algorithm (Method 1)

Let’s see the palindrome program in java. In this java program, we will get a number variable and check whether number is palindrome or not.

class PalindromeExample{  

 public static void main(String args[]){  

  int r,sum=0,temp;    

  int n=454;//It is the number variable to be checked for palindrome  

  

  temp=n;    

  while(n>0){    

   r=n%10;  //getting remainder  

   sum=(sum*10)+r;    

   n=n/10;    

  }    

  if(temp==sum)    

   System.out.println(“palindrome number “);    

  else    

   System.out.println(“not palindrome”);    

}  

}  

Output:

palindrome  number

Here we have done the following check and the output is achieved as the "Palindrome Number"


Input number to check for palindrome
Store the number in temp variable
Reverse the number with calculation
Compare the stored temp number with number just reversed 
Check with condition , if both the numbers are same , print "palindrome number"
Otherwise print "No palindrome found"

Palindrome Program in Java (Method 2)

In Palindrome Program in Java , You can also use a method to find where number or string is not predefined. Here, user has to put the number or string as input to check if the number/string is palindrome.

In this program,

  • First, given number (num)’s value is stored in another integer variable, originalInteger. This is because, we need to compare the values of reversed number and original number at the end.
  • Then, a while loop is used to loop through num until it is equal to 0.
    • On each iteration, the last digit of num is stored in the remainder.
    • Then, the remainder is added to reversedInteger such that it is added to the next place value (multiplication by 10).
    • Then, the last digit is removed from num after division by 10.
  • Finally, reversedInteger and originalInteger are compared. If equal, it is a palindrome number. If not, it isn’t.

import java.util.*;   

class PalindromeExample2  

{  

   public static void main(String args[])  

   {  

      String original, reverse = “”; // Objects of String class  

      Scanner in = new Scanner(System.in);   

      System.out.println(“Enter a string/number to check if it is a palindrome”);  

      original = in.nextLine();   

      int length = original.length();   

      for ( int i = length – 1; i >= 0; i– )  

         reverse = reverse + original.charAt(i);  

      if (original.equals(reverse))  

         System.out.println(“Entered string/number is a palindrome.”);  

      else  

         System.out.println(“Entered string/number isn’t a palindrome.”);   

   }  

}  

Output:Use image PalindromeExample

2.2. Reversing the String

There are a few different implementations that fit this use case: we can make use of the API methods from StringBuilder and StringBuffer classes when checking for palindromes, or we can reverse the String without these classes.

Let’s take a look at the code implementations without the helper APIs first:

public boolean isPalindromeReverseTheString(String text) {
    StringBuilder reverse = new StringBuilder();
    String clean = text.replaceAll("\\s+", "").toLowerCase();
    char[] plain = clean.toCharArray();
    for (int i = plain.length - 1; i >= 0; i--) {
        reverse.append(plain[i]);
    }
    return (reverse.toString()).equals(clean);
}

In the above snippet, we simply iterate the given String from the last character and append each character to the next character, all the way through to the first character thereby reversing the given String.

Finally, we test for equality between the given String and reversed String.

The same behavior could be achieved using API methods.

Let’s see a quick demonstration:

public boolean isPalindromeUsingStringBuilder(String text) {
    String clean = text.replaceAll("\\s+", "").toLowerCase();
    StringBuilder plain = new StringBuilder(clean);
    StringBuilder reverse = plain.reverse();
    return (reverse.toString()).equals(clean);
}

public boolean isPalindromeUsingStringBuffer(String text) {
    String clean = text.replaceAll("\\s+", "").toLowerCase();
    StringBuffer plain = new StringBuffer(clean);
    StringBuffer reverse = plain.reverse();
    return (reverse.toString()).equals(clean);
}

In the code snippet, we invoke the reverse() method from the StringBuilder and StringBuffer API to reverse the given String and test for equality.

2.3. Using Stream API

We can also use an IntStream to provide a solution:

public boolean isPalindromeUsingIntStream(String text) {
    String temp  = text.replaceAll("\\s+", "").toLowerCase();
    return IntStream.range(0, temp.length() / 2)
      .noneMatch(i -> temp.charAt(i) != temp.charAt(temp.length() - i - 1));
}

In the snippet above, we verify that none of the pairs of characters from each end of the String fulfills the Predicate condition.

2.4. Using Recursion

Recursion is a very popular method to solve these kinds of problems. In the example demonstrated we recursively iterate the given String and test to find out whether it’s a palindrome or not:

public boolean isPalindromeRecursive(String text){
    String clean = text.replaceAll("\\s+", "").toLowerCase();
    return recursivePalindrome(clean,0,clean.length()-1);
}

private boolean recursivePalindrome(String text, int forward, int backward) {
    if (forward == backward) {
        return true;
    }
    if ((text.charAt(forward)) != (text.charAt(backward))) {
        return false;
    }
    if (forward < backward + 1) {
        return recursivePalindrome(text, forward + 1, backward - 1);
    }

    return true;
}

3. Conclusion

Given Above programs can be used to calculate the Palindrome string in JAVA. Palindrome Program in Java is used to identify the valid string or number is palindrome. you can use the below to calculate the complexity

Complexity Analysis:  

  • Time complexity: O(n^2). 
    Two nested traversals are needed.
  • Auxiliary Space: O(n^2). 
    Matrix of size n*n is needed to store the dp array.