Converting String to StringBuilder in Java

JavaObject Oriented ProgrammingProgramming

The append() method of the StringBuilder class accepts a String value and adds it to the current object.

To convert a String value to StringBuilder object −

  • Get the string value.

  • Append the obtained string to the StringBuilder using the append() method.

Example

In the following Java program, we are converting an array of Strings to a single StringBuilder object.

 Live Demo

public class StringToStringBuilder {
   public static void main(String args[]) {
      String strs[] = {"Arshad", "Althamas", "Johar", "Javed", "Raju", "Krishna" };
      StringBuilder sb = new StringBuilder();
      sb.append(strs[0]);
      sb.append(" "+strs[1]);
      sb.append(" "+strs[2]);
      sb.append(" "+strs[3]);
      sb.append(" "+strs[4]);
      sb.append(" "+strs[5]);
      System.out.println(sb.toString());
   }
}

Output

Arshad Althamas Johar Javed Raju Krishna
raja
Published on 15-Oct-2019 11:07:26
Advertisements