Friday, November 19, 2021

Check if Given String or Number is a Palindrome Java Program

This post is about writing a Java program to find that a given string or number is a palindrome or not.

Remember a String or a number is a palindrome if it remains unchanged when reversed, for example "madam" is a palindrome as reverse of the madam is again madam. Another example is "malayalam" or 12344321.


Logic for finding if String palindrome or not

Here three ways are given to check whether given string is a palindrome or not in Java. First 2 ways use the inbuilt String functions to do that.

In the first method checkPalindrome1(), StringBuilder class instance is used which is instantiated using the given String, then the inbuilt reverse method of the StringBuilder is used. If the given string is a palindrome then reverse of the string should be same as the original string.

Second method checkPalindrome2() is same as the first method, it works on the logic that the second half of the string is the mirror image of the first half so if second half of the string is reversed then it should be same as the first half.
As example: If we have a string 12344321 then the second half 4321 if reversed will become 1234 which is equal to the first half, thus string is a palindrome.
In this logic whether a given string is of even length or odd length matters. That's why the ternary operator while creating the StringBuilder object.

index + index == str.length() ? str.substring(index) : str.substring(index + 1)

Third method checkPalindrome3() doesn't use any inbuilt function. In this method we start from the end of the string and read one character at a time to create a new String. Now if a given string is a palindrome then the new string should be equal to the original string.

Given String palindrome or not Java program

public class Palindrome {
  public static void main(String[] args) {
    Palindrome pm = new Palindrome();
    pm.checkPalindrome1("DogeeseseeGod");
    pm.checkPalindrome2("malayalam");
    pm.checkPalindrome3("1234442");
  }
    
  private void checkPalindrome1(String str){            
    StringBuilder sb = new StringBuilder(str);
    // reverse the string and check if it is equal to original 
    // string
    if(str.equalsIgnoreCase(sb.reverse().toString())){
      System.out.println(str + " is a Palindrome");
    }else{
      System.out.println(str + " is not a Palindrome");
    }        
  }
    
  /**
  * In a palindrome one half of the string is the mirror image of the other
  * this logic is based on that
  * @param str
  */
  private void checkPalindrome2(String str){        
    int index = str.length()/2;        
    StringBuilder sb = new StringBuilder(index + index == str.length() 
          ? str.substring(index) : str.substring(index + 1));
    if(str.substring(0, index).equalsIgnoreCase(sb.reverse().toString())){
      System.out.println(str + " is a Palindrome");
    }else{
      System.out.println(str + " is not a Palindrome");
    }        
  }        
    
  /**
  * If no inbuilt function has to be used.
  * 
  * @param str
  */
  private void checkPalindrome3(String str){
    StringBuilder sb = new StringBuilder();
    // start reading the string backward
    for(int i = str.length() - 1; i >= 0; i--){
      sb.append(str.charAt(i));
    }            
    System.out.println("string 3 " + sb.toString());
    if(str.equalsIgnoreCase(sb.toString())){
      System.out.println(str + " is a Palindrome");
    }else{
      System.out.println(str + " is not a Palindrome");
    }    
  }
}

Output

DogeeseseeGod is a Palindrome
malayalam is a Palindrome
string 3 2444321
1234442 is not a Palindrome

Java program to check if number palindrome or not

Though we can convert number to string and use any of the above mentioned methods to verify if given number is a palindrome or not but in a scenario where we have to do it for number this program can be used.

public class PalindromeNumber {

  public static void main(String[] args) {
    PalindromeNumber pm = new PalindromeNumber();
    pm.checkNumberPalindrome(12344321);
    pm.checkNumberPalindrome(12322);
  }
 
  /**
  * To check for integers
  * @param num
  */
  private void checkNumberPalindrome(int num){
    int reverse = 0;
    int remainder;
    int originalNum = num;
    // reversing the number
    while (num > 0) {
      remainder = num % 10;
      reverse = (reverse * 10) + remainder;
      num = num / 10;
    }
    if(reverse == originalNum){
      System.out.println(originalNum + " is a Palindrome");
    }else{
      System.out.println(originalNum + " is not a Palindrome");
    }
  }
}

Output

12344321 is a Palindrome
12322 is not a Palindrome

That's all for this topic Check if Given String or Number is a Palindrome Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. How to Find The Longest Palindrome in The Given String
  2. Check Given Strings Anagram or Not Java Program
  3. Count Number of Words in a String Java Program
  4. Add Double Quotes to a String Java Program
  5. Print Odd-Even Numbers Using Threads And wait-notify Java Program

You may also like-

  1. Find Largest and Second Largest Number in Given Array Java Program
  2. Method Overloading in Java
  3. Encapsulation in Java
  4. Race Condition in Java Multi-Threading
  5. Callable and Future in Java With Examples
  6. Java ReentrantLock With Examples
  7. How HashMap Works Internally in Java
  8. Dependency Injection in Spring Framework

1 comment:

  1. Checking for Numbers
    import java.util.*;
    public class test
    {
    public static void main(String args[])
    {
    Scanner scan=new Scanner(System.in);
    int n=scan.nextInt();
    Stackstk=new Stack();
    int c=n;
    int flag=0;

    while(n>0)
    {
    stk.add(n%10);
    n=n/10;
    }

    while(!stk.isEmpty())
    {
    int k=stk.pop();
    if(k==c%10)
    {
    flag=1;
    }
    c=c/10;
    }
    if(flag==1)
    System.out.println("PALINDROME");
    else
    System.out.println("NOT palindrome");
    }
    }

    ReplyDelete