Thursday, 8 October 2015

Java program to reverse the order of the string using StringBuffer Class

Requirement: I have a string and when I run the Java program the output should be displayed in the reverse order (say if the string is Susanto it should give the output as otnasuS).

Solution: The Java program of the above requirement is shown in the the earlier post. But  I want to reverse the string using the StringBuffer class. The Java program to reverse the string using StringBuffer class is shown below.

Program 1:
package com.susanto;

public class ReverseString {

      public static void main(String[] args) {
            StringBuffer stringToReverse1 = new StringBuffer("Susanto");
            stringToReverse1.reverse();
           System.out.println("Thus the reversedString is : " +stringToReverse1);
           // -------------------------------------------------------------------
            String stringToReverse2 = "Moumita Deb";
            String reverseString2 = new StringBuffer(stringToReverse2).reverse()
                        .toString();
            System.out.printf("Original String : %s , Reversed String %s  %n",
                        stringToReverse2, reverseString2);
      }
}

Output:
Thus the reversedString is : otnasuS
Original String : Moumita Deb , Reversed String beD atimuoM 


Program 2:

package com.susanto;

public class ReverseString {
      private static void reverseString() {
            String originalString = "Susanto Paul";
            System.out.println("The original string is: " + originalString);
            StringBuffer reversedString = new StringBuffer(originalString)
                        .reverse();
            System.out.println("Reversed string is : " + reversedString);
      }

      public static void main(String[] args) {
            reverseString();
      }

}

Output:
The original string is: Susanto Paul
Reversed string is : luaP otnasuS



Thanks & Regards,
Susanto Paul