JAVA StringBuffer and StringBuilder object conversion to String

We can convert a StringBuffer or StringBuilder object to String by using toString() method of Object class.

StringConversion.java

class StringConversion {
    public static void main(String[] args) {
        StringBuffer sb1 = new StringBuffer("Silan");
        StringBuilder sb2 = new StringBuilder("Technology");
        String s1 = sb1.toString();
        String s2 = sb2.toString();
        System.out.println(s1 + " " + s2);     
    }
}

Output:


Another Example:
StringConversion1.java

class StringConversion1 {
    public static void main(String[] args) {
        StringBuffer sb1 = new StringBuffer("Silan");
        StringBuffer sb2 = new StringBuffer("Silan");
        String s1 = sb1.toString();
        String s2 = sb2.toString();
        if (s1.equals(s2)); {
            System.out.println("s1 and s2 contents are equal");
        } else {
            System.out.println("s1 and s2 contents are not equal");
        }
    }
}

Output:

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Data Science with Python Training | Projects

SILAN Technology, BBSR
Call to: 0674-2361252

Comment