How to Convert a StringBuilder to a String in Java

In this post, I will be sharing how to convert StringBuilder to String in Java. I have already shared the difference between String and StringBuilder in Java.

There are two ways to convert StringBuilder to String:
1. Using StringBuilder class toString() method [Recommended]
2. Using Constructor

Read Also: String Interview Questions and Answers

Convert a StringBuilder to a String in Java

1. Using StringBuilder class toString() method

The easiest way to convert StringBuilder to String is by invoking the toString() method of the StringBuilder class.
Below are the steps:
a. Create an object of StringBuilder class
b. Append the data to the StringBuilder object by using the append() method.
c. Call toString() method on the StringBuilder object.

 public class StringBuilderToString {
    public static void main(String args[]) {
      StringBuilder sb = new StringBuilder();
      sb.append("Hello World");
      String result = sb.toString();
      System.out.println(result);
    }
}

Output:
Hello World

2. Using String class constructor

Another way to convert StringBuilder to String in Java is by using the String class constructor. Please find the example below:
 public class StringBuilderToString2 {
    public static void main(String args[]) {
      StringBuilder sb = new StringBuilder();
      sb.append("Java Developer");
      String result = new String(sb);
      System.out.println(result);
    }
}


Output:
Java Developer

That's all for today, please mention in the comments in case you have any questions related to how to convert a StringBuilder to a String in Java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry