Java StringBuilder.toString() – Examples

In this tutorial, we will learn about the Java StringBuilder.toString() function, and learn how to use this function with the help of examples.

toString()

Java StringBuilder.toString() returns a string representing the data in this sequence.

ADVERTISEMENT

Syntax

The syntax of toString() function is

toString()

Returns

The function returns String object.

Example 1 – toString()

In this example, we will create a StringBuilder object and initialize with some string passed as argument. We will get the string from the StringBuilder using toString() method.

Java Program

class Example { 
    public static void main(String[] args) { 
   
        // create a StringBuilder object 
        // with a String passed as parameter 
        StringBuilder stringBuilder = new StringBuilder("foo bar"); 
   
        String str = stringBuilder.toString();
        System.out.println(str); 
    } 
}

Output

foo bar

Example 2 – toString()

In this example, we will create a StringBuilder object and initialize with some string passed as argument.

We will then append another string to this StringBuilder object.

Then, we will get the string from the StringBuilder using toString() method.

Java Program

class Example { 
    public static void main(String[] args) { 
        // create a StringBuilder object 
        // with a String passed as parameter 
        StringBuilder stringBuilder = new StringBuilder("foo bar"); 
        stringBuilder.append(" car");
         
        String str = stringBuilder.toString();
        System.out.println(str); 
    } 
}

Output

foo bar car

Conclusion

In this Java Tutorial, we have learnt the syntax of Java StringBuilder.toString() function, and also learnt how to use this function with the help of examples.