June 22, 2022

Java Program to Check Given String Palindrome or Not

In this post we’ll see how to write a Java program to check whether a given string is palindrome or not.

A string is said to be a palindrome if it remains same when reversed as example mom, malayalam.

Given String Palindrome or not - Java program

In order to find if a given string is palindrome or not in Java, you can use reverse() method of the StringBuider class to reverse the String and then compare it with original String. If both are same then the passed String is a palindrome.

If you are specifically asked not to use any inbuilt method in Java then you can build a reverse string by reading the passed string backward. In the below Java program solution using both of the above options is given.

public class Palindrome {

  public static void main(String[] args) {
    checkPalindromeReverse("malayalam");
    checkPalindromeReverse("code");
    System.out.println("------------");
    checkPalindrome("mom");
    checkPalindrome("12321");
    checkPalindrome("test");
  }

  // Method using StringBulider class reverse method
  private static void checkPalindromeReverse(String str){
    StringBuilder sb = new StringBuilder(str);
    // reverse the string and compare with original 
    // to check if strings are same
    if(str.equalsIgnoreCase(sb.reverse().toString())){
      System.out.println(str + " is a Palindrome");
    }else{
      System.out.println(str + " is not a Palindrome");
    }       
  }

  private static void checkPalindrome(String str){
    StringBuilder sb = new StringBuilder();
    // read string backward
    for(int i = str.length() - 1; i >= 0; i--){
      sb.append(str.charAt(i));
    }            
    if(str.equalsIgnoreCase(sb.toString())){
      System.out.println(str + " is a Palindrome");
    }else{
      System.out.println(str + " is not a Palindrome");
    }
  }
}
Output
malayalam is a Palindrome
code is not a Palindrome
------------
mom is a Palindrome
12321 is a Palindrome
test is not a Palindrome

That's all for the topic Java Program to Check Given String Palindrome or Not. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment