Convert StringBuffer to String

After knowing the differences between String, StringBuffer and StringBuilder, let us Convert StringBuffer to String and vice versa. It is very much required in coding.
Convert StringBuffer to String

A StringBuffer object can be converted to String using toString() method of Object class.

StringBuffer sb1 = new StringBuffer("hello");
StringBuffer sb2 = new StringBuffer("hello");

String str1 = sb1.toString();
String str2 = sb2.toString();

    System.out.println(“sb1 and sb2 both are same”);
    System.out.println(“sb1 and sb2 both are not same”);

In the above code, equals() method is to be applied on String objects but not on StringBuffer objects; that is, sb1.euqals(sb2) raises error. So, to compare two StringBuffer objects, it is required to convert them into strings.

String to StringBuffer

Sometimes it is also required to convert String to StringBuffer also. Suppose, if you would like to delete a few characters from a string, the String should be converted into a StringBuffer as delete() is method of StringBuffer and not String. delete() method of StringBuffer deletes a group of characters.

       String str1 = "abcdefghi";
       StringBuffer sb1 = new StringBuffer(str1);
       sb1.delete(3, 6);             // deleted def
       System.out.println(sb1);      // prints abcghi

Suppose, if you would like to have string back again, convert with toString() method as done earlier.

       String str2 = sb1.toString();
       System.out.println(str2);  // prints abcghi

Now you got the string str2 from str1 after deleting some characters (intermittently we used StringBuffer).

Leave a Comment

Your email address will not be published.