Convert StringBuffer to String

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.

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.

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *