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.