2 ways to Convert String to StringBuilder in Java

In this post, I will be sharing how to convert String to StringBuilder in Java. I have already shared the String interview questions and answers for freshers and experienced.

There are two ways to convert String to StringBuilder in Java.
1. Using StringBuilder class constructor
2. Using append method

Read Also: Convert StringBuilder to String in Java

Convert String to StringBuilder in Java


1. Using StringBuilder class constructor


To convert String to StringBuilder in Java you can use a StringBuilder class constructor that accepts String.

Syntax

 public StringBuilder(CharSequence sequence)

Example

 public class StringToStringBuilder {
    public static void main(String args[]) {
      // Given String    
      String str = "Alive is Awesome";    
      // Converting String to StringBuilder using constructor 
      StringBuilder sb = new StringBuilder(str);
      // Printing StringBuilder object
      System.out.println(sb);
    }
}

Output:
Alive is Awesome


2. Using append method


To convert String to StringBuilder object, you can use the StringBuilder class append() method. According to Oracle docs, the append() method accepts a String value and add it to the current object as shown in the below example:

Example

 public class StringToStringBuilder2 {
    public static void main(String args[]) {
      // Original String    
      String str = "Love Yourself";
      // Creating StringBuilder object
      StringBuilder sb = new StringBuilder();
      /* Using append() method to convert String to 
      StringBuilder */
      sb.append(str);
      // Printing StringBuilder object
      System.out.println(sb);
    }
}

Output:
Love Yourself


That's all for today, please mention in the comments in case you know any other way to convert String to StringBuilder 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