reverse() StringBuffer Example

java.lang.StringBuffer class comes with many utility methods to manipulate string. One of the method is reverse() used to reverse the contents of the buffer. After this method call, original buffer itself gets effected.

Note: reverse() is not a method of String; applying on string raises compilation error.

What Java API says about reverse() StringBuffer:
  • public synchronized StringBuffer reverse(): Reverses the contents of the buffer. Returns a StringBuffer object. The returned object and the original buffer object, both contain the reversed string only. See example.

Following example illustrates the usage of reverse() StringBuffer method in all possible ways.

public class Demo
{
  public static void main(String args[])
  {					  
   StringBuffer sb1 = new StringBuffer("ABCDEF");    
   System.out.println("Buffer sb1 contents before reverse: " + sb1);

   StringBuffer sb2 = sb1.reverse();

   System.out.println("Buffer sb1 contents after  reverse: " + sb1);
   System.out.println("Returned StringBuffer sb2 contents: " + sb2);
 }
}


reverse() StringBuffer
Output screenshot of reverse() StringBuffer

Another example on reverse() method. It is to reverse a string and check for a Palindrome.

public class Demo
{
  public static void main(String args[])
  {
   String str1 = "radar";					  
   StringBuffer sb1 = new StringBuffer(str1);   
   sb1.reverse();
   String str2 = sb1.toString();

   if(str1.equals(str2))
   { 
     System.out.println("YES, " + str1 + " is Palindrome");
   }
   else
   {
     System.out.println("NO, " + str1 + " is not Palindrome");
   }
 }
}


reverse() StringBuffer
Output screenshot of Palindrome of reverse() StringBuffer

StringBuffer sb1 = new StringBuffer(str1);
sb1.reverse();

Reverse is not a method of String class but of StringBuffer. For this reason, String str1 is converted into a StringBuffer object sb1 and then reversed.

String str2 = sb1.toString();

Again after reversing, the StringBuffer object sb1 is converted to String, with toString() method, to compare with the original String object str1. The whole can be converted into simple code using anonymous objects as follows.

public class Demo
{
  public static void main(String args[])
  {
   String str1 = "radar";					  

   if(str1.equals(new StringBuffer(str1).reverse().toString()))
   { 
     System.out.println("YES, " + str1 + " is Palindrome");
   }
   else
   {
     System.out.println("NO, " + str1 + " is not Palindrome");
   }
 }
}

Leave a Comment

Your email address will not be published.