How to convert String to StringBuilder and vice versa Java?


The String type is a class in Java, it is used to represent a set of characters. Strings in Java are immutable, you cannot change the value of a String once created.

Since a String is immutable, if you try to reassign the value of a String. The reference of it will be pointed to the new String object leaving an unused String in the memory.

Java provides StringBuffer class as a replacement of Strings in places where there is a necessity to make a lot of modifications to Strings of characters.

You can modify/manipulate the contents of a StringBuffer over and over again without leaving behind a lot of new unused objects.

The StringBuilder class was introduced as of Java 5 and the main difference between the StringBuffer and StringBuilder is that StringBuilder’s methods are not thread safe (not synchronized).

It is recommended to use StringBuilder whenever possible because it is faster than StringBuffer. However, if the thread safety is necessary, the best option is StringBuffer objects.

Converting a String to StringBuilder

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 just append it using the append() method.

Example

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

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

Converting a StringBuilder to String

The toString() method of the StringBuilder class reruns String value of the current object. To convert a StringBuilder to String value simple invoke the toString() method on it.

Example

In the following Java program we are converting an array of Strings to a singleStringusing the toString() method of the StringBuilder.

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]);
      String singleString = sb.toString();
      System.out.println(singleString);
   }
}

Output

Arshad Althamas Johar Javed Raju Krishna
raja
Published on 01-Aug-2019 16:13:32
Advertisements