Frequently Asked Java Program 03: Java Program to check if any string is palindrome Using inbuilt Reverse method of Java

Hello Folks,

As part of Frequently Asked Java Programs In Interviews For Freshers And Experienced,  in this post we will see a Java program to verify if a given string is palindrome using inbuilt reverse method.

WHAT IS PALINDROME STRING?

A palindromic string is a string that remains the same when its characters are reversed.

For Example: NAAN, AMMA  etc.

Logic:

  • Java provides two classes StringBuilder and StringBuffer who has reverse() method. Note here that String class has no reverse method.
  • We can convert any string to StringBuilder or StringBuffer using their constructors.
  • There is a trick to compare content of two objects of StringBuffer or StringBuilder which is discussed in below program.

Java Program:

Output:

Please enter the string to know palindrome:
AMMA
Result:Palindrome
Result:Palindrome
Result:Palindrome

Please enter the string to know palindrome:
NANA
Result:Not Palindrome
Result:Not Palindrome
Result:Not Palindrome

Please enter the string to know palindrome:
AMMA AMMA
Result:Palindrome
Result:Palindrome
Result:Palindrome

 

You can run above program for multiple inputs and if it fails for any condition, let me know.

#HappyCoding

Author: Amod Mahajan

A software Tester who is paid to judge products developed by others. Writing technical posts and creating YouTube videos are my hobbies.

1 thought on “Frequently Asked Java Program 03: Java Program to check if any string is palindrome Using inbuilt Reverse method of Java

  1. We can also use below approach:

    public static void main(String[] args) {

    System.out.println(“Enter the input string”);
    Scanner sc = new Scanner(System.in);
    String inputString = sc.next();

    sc.close();

    String temp = inputString;
    StringBuilder str = new StringBuilder(temp).reverse();

    if (inputString.equals(str.toString()))
    {
    System.out.println(“Is palindrome using StringBuilder”);
    }

    else {
    System.out.println(“String is not Palindrome !!”);
    }

    }

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.