How to check Palindrome String in java?


StringBuffer provides a method with name reverse() one way to check for a palindrome is

  • Create a StringBuffer object by passing the required string as a parameter to the constructor.
  • Reverse the contents of the object using the reverse() method.
  • Convert the StringBuffer object to Sting using the toString() method.
  • Now, compare the String and the reversed one, if true, the given string is a palindrome.

Example

Live Demo

public class StringPalindrome {
   public static void main(String args[]) {
      String myString = "anna";
      StringBuffer buffer = new StringBuffer(myString);
      buffer.reverse();
      String data = buffer.toString();
      if(myString.equals(data)){
         System.out.println("Given String is palindrome");
      } else {
         System.out.println("Given String is not palindrome");
      }
   }
}

Output

Given String is palindrome

Updated on: 26-Feb-2020

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements