How to find if a string is a palindrome using Java?

Java 8Object Oriented ProgrammingProgramming

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

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


Live Demo

public class StringPalindrome {
   public static void main(String args[]){

      String myString = "anna";
      StringBuffer buffer = new StringBuffer(myString);
      String data = buffer.toString();
         System.out.println("Given String is palindrome");
         System.out.println("Given String is not palindrome");


Given String is palindrome
Updated on 30-Jul-2019 22:30:20