When a lot of changes are required in data, which one you choose String or StringBuffer in 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

Updated on: 05-Aug-2019

479 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements