StringBuffer and StringBuilder

How to Change From StringBuffer and StringBuilder to String and vice versa ??

Last updated:7/21/2018 6:05:08 AM

1 Answers

Prakash nidhi Verma
Prakash nidhi Verma

From StringBuffer and StringBuilder to String :

using toString() method which is overridden in both StringBuffer and StringBuilder classes.means the subsequent changes to the StringBuffer object do not affect the contents of the String object. 

public class Test  
{
    public static void main(String[] args)
    {
        StringBuffer sbr = new StringBuffer('mindstick');
        StringBuilder sbdr = new StringBuilder('software');
        // conversion from StringBuffer object to String
        String str = sbr.toString();
        System.out.println('StringBuffer object to String : ');
        System.out.println(str);
        // conversion from StringBuilder object to String
        String str1 = sbdr.toString();
        System.out.println('StringBuilder object to String : ');
        System.out.println(str1);
        sbr.append('for software development');
        System.out.println(sbr);
        System.out.println(str);
    }
}

From StringBuffer to StringBuilder or vice-versa :  

There is no direct way to convert the same. We firstconvert StringBuffer/ StringBuilder object to String using toString() method  

public class Test  
{
    public static void main(String[] args)
    {
        StringBuffer sbr = new StringBuffer('mindstick');
        //conversion from StringBuffer object to StringBuilder
        String str = sbr.toString();
        StringBuilder sbl = new StringBuilder(str);
        System.out.println(sbl);
    }
}

Answer