Convert String to StringBuffer in Java [2 ways]

In this post, I will be sharing how to convert String to StringBuffer in Java. I have already shared the difference between String, StringBuilder, and StringBuffer in Java. There are two ways to achieve our goal:

1. Using StringBuffer class constructor

2. Using StringBuffer class append() method

Read Also: Convert String to StringBuilder in Java

Let's dive deep into the topic:

Convert String to StringBuffer in Java

1. Using StringBuffer class constructor


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

Syntax


 public StringBuffer(String str)


Example:


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

Output:
Converted String to StringBuffer: Alive is Awesome


2. Using StringBuffer class append method


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

Example


 public class StringToStringBuffer2 {
    public static void main(String args[]) {
      // Given String 
      String str = "Be in present";
      // Creating StringBuffer object
      StringBuffer sb = new StringBuffer();
      // Converting String to StringBuffer using append() method
      sb.append(str);
      // Displaying StringBuffer object
      System.out.println("Converted String to StringBuffer: " + sb);
    }
}

Output:
Converted String to StringBuffer: Be in present

That's all for today. Please mention in the comments if you have any questions related to how to convert String to StringBuffer in Java with examples.

About The Author

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