String palindrome in java using stringbuffer

Let’s learn string palindrome in java using stringbuffer.

String palindrome in java using stringbuffer

Let’s learn to find if a string is a palindrome using StringBuffer. First we have to create StringBuffer object ‘sb’. Then pass given string as parameter to the constructor.

Now reverse contents of given string using reverse() method of StringBuffer class. In the next step convert StringBuffer object to String using toString() method of String class.

Finally compare reversed string and given string. If both are same, string is palindrome else string is not palindrome. Let’s see an example

public class PalindromeUsingStringBuffer
{
   public static void main(String[] args)
   {
      String strInput = "nayan";
      StringBuffer sb = new StringBuffer(strInput);
      sb.reverse();
      String str = sb.toString();
      if(strInput.equals(str))
      {
         System.out.println(str + " string is palindrome.");
      }
      else
      {
         System.out.println(str + " string is not palindrome.");
      }
   }
}


Output:

nayan string is palindrome.


Also read – polymorphism in java