StringBuilder To String Java

StringBuilder To String Java | The StringBuilder in Java is the mutable sequence of characters. The string is immutable which means we cannot make any changes to the string object once created, after any changes, it will create a new object but the StringBuilder allows us to edit the string literal without creating a new object. The StringBuilder is non-synchronized and it is single-threaded.

The conversion of StringBuilder to String can be done in two following ways:-

  1. Using the toString() method of the StringBuilder class
  2. Using String class constructor

The first method we use is the StringBuilder toString() method, it converts the StringBuilder object to String. The syntax of the toString method is as follows:- public String toString()

Java StringBuilder To String Using toString() Method

Let us see some examples for conversion of StringBuilder to String using the toString() method.

public class Main {
   public static void main(String[] args) {
      StringBuilder sb = new StringBuilder("Hello, Good Morning.");
      System.out.println("StringBuilder: " + sb);
      System.out.println("Type: " + sb.getClass().getName());

      // calling toString() method
      String string = sb.toString();
      System.out.println("String: " + string);
      System.out.println("Type: " + string.getClass().getName());
   }
}

Output:

StringBuilder: Hello, Good Morning.
Type: java.lang.StringBuilder
String: Hello, Good Morning.
Type: java.lang.String

public class Main {
   public static void main(String[] args) {
      StringBuilder sb = new StringBuilder("Java Programmer");
      System.out.println("String: " + sb.toString());
   }
}

Output:-

String: Java Programmer

StringBuilder To String Java using String class Constructor

We can use the String class constructor String(StringBuilder builder) to convert StringBuilder to String. This constructor creates a new string and allocates the character sequence of the StringBuilder class to the new string.

Program to convert StringBuilder to String in Java using String class Constructor

public class Main {
   public static void main(String[] args) {
      StringBuilder str = new StringBuilder("Know Program");
      String str1 = new String(str);
      System.out.println(str1);
   }
}

Output:-

Know Program

Another example of the constructor of String(StringBuilder builder),

public class Main {
   public static void main(String[] args) {
      StringBuilder str = new StringBuilder();
      str.append("Life is too short to argue just say ok and move on.");
      String str1 = new String(str);
      System.out.println(str1);
   }
}

Output:-

Life is too short to argue just say ok and move on.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published.