StringBuilder Class in Java

The StringBuilder Class

The StringBuilder objects same as the StringBuffer objects. The StringBuilder objects are also mutable. It is the non synchronized class and available since JDK 1.5.

StringBuilder Class Constructors

StringBuilder class functionality is exactly same as StringBuffer class. So it also has same StringBuffer parameter constructor as shown below.

1. public StringBuild() : It creates an empty string builder object with initial capacity of 16.  

2. public StringBuilder(int capacity) : It is used to create an empty string builder object with initial specified capacity.

3. public StringBuilder(String s) : This constructor creates a string builder object whose value is initialized by the specified string, plus an extra 16 empty elements trailing by the string.

4. public StringBuilder(CharSequence cs) : It constructs a string builder object that contains same characters as the specified in CharSequence, plus extra 16 elements trailing the charSequence.

StringBuilder Methods

There are some important methods which are supported by StringBuilder class.

MethodsDescription
public StringBuilder append(String s)Append the specified string with the given string.
public StringBuilder insert(int offset, String s)Insert the specified string with given string at the specified position.
public StringBuilder delete(int start, int end)Delete substring from specified start index to end index.
public StringBuilder replace(int start, int end, String s)Replace the characters in a substring of current sequence with the character in the specified new string.
public StringBuilder reverse()Reverse the given string.
public StringBuilder toString()Returns a string representing the data in this sequence.
void setLength(int newLength)Set the length of the character sequence. The value of argument newLength is always positive, otherwise it will throw IndexOutOfBoundException.
public ensureCapacity(int minimumCapacity)Ensure that the capacity is at least equal to given minimum capacity.

NOTE:
StringBuffer and StringBuilder both are same in functionality except that StringBuffer is synchronized i.e. thread-safe and StringBuilder is non-synchronized i.e. not thread-safe.

Example : A program to illustrate different StringBuilder methods

public class StringBuilderDemo
{
      public static void main(String args[])
      {
            StringBuilder sb1 = new StringBuilder("Tutorial");
            StringBuilder sb2 = new StringBuilder("Java Toturials");
            StringBuilder sb3 = new StringBuilder("Welcome");
            StringBuilder sb4 = new StringBuilder("ABC");
            //append
            sb1.append("Ride");
            System.out.println("sb1: "+sb1);
            //delete
            sb2.delete(0, 5);
            System.out.println("After delete sb1= "+sb2);
            //reverse
            sb3.reverse();
            System.out.println("Reverse of sb2= "+sb3);
            //charAt()
            for (int i = 0; i <= sb4.length()-1; i++)
            {
                  System.out.println("Character at index "+i+" is: "+sb4.charAt(i));
            }
      }
}


Output:
sb1: TutorialRide
After delete sb1= Toturials
Reverse of sb2= emocleW
Character at inedx 0 is: A
Character at inedx 1 is: B
Character at inedx 2 is: C

Difference between String and StringBuffer Class.

StringStringBuilder
The object of String class is immutable.The object of Stringbuffer class is mutable.
Creates string in fixed size.Creates string in dynamically flexible.
The performance of String class is slow when performing concatenation.It performs better while performing concatenation.
Growing and shrinking in size is not possible.Growing and shrinking in size is possible.
String class overrides the equals () method of object class.StringBuffer class doesn’t override the equals ().

Example

//Write a program to check the performance of String and StringBuilder while concatenation.

public class ConcatTest
{
     public static String concatWithString()
    {
         String s = "Tutorial";
         for (int i=0; i<10000; i++)
         {
               s = s + "Ride";
         }
         return s;
    }
    public static String concatWithStringBuffer()
    {
         StringBuffer sb = new StringBuffer("Tutorial");
         for (int i=0; i<10000; i++)
         {
               sb.append("Ride");
         }
         return sb.toString();
    }
    public static void main(String[] args)
    {
         long start = System.currentTimeMillis();
         concatWithString();
         System.out.println("Time taken by String: " + (System.currentTimeMillis() - start) + "ms");
         start = System.currentTimeMillis();
         concatWithStringBuffer();
         System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - start) + "ms");
    }
}


Output:
Time taken by String: 641ms
Time taken by StringBuffer: 1ms