StringBuffer in Java with Examples

The StringBuffer class in java is the same as the String class except it is mutable i.e. it can be changed.

A thread-safe, mutable sequence of characters. A string buffer is like a String but can be modified. At any point in time, it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.

If the content will change frequently then never recommended going for String object because for every change a new object will be created internally.

The main advantage of StringBuffer over String is, all required changes will be performed in the existing object only instead of creating a new object. (won't create new object')

String buffers are safe for use by multiple threads.

The principal operations on a StringBuffer are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string buffer.

Every string buffer has a capacity. As long as the length of the character sequence contained in the string buffer does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the internal buffer overflows, it is automatically made larger.

As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.

Passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

Every method present in StringBuffer is synchronized hence at a time only one thread is allowed to operate on the StringBuffer object, it increases the waiting time of the threads and creates performance problems, to overcome this problem we should go for StringBuilder.

StringBuffer Class Declaration

The following is the declaration for java.lang.StringBuffer class:

public final class StringBuffer extends Object implements Serializable, CharSequence

StringBuffer Constructors

StringBuffer has 4 constructors.

1). StringBuffer sb = new StringBuffer(); 

 It creates an empty StringBuffer object with a default initial capacity "16". Once the StringBuffer object reaches its maximum capacity a new StringBuffer object will be created with newCapacity = (currentcapacity+1)*2.

public class StringBuffer1 { public static void main(String[] args) { StringBuffer sb = new StringBuffer(); System.out.println(sb.capacity()); //16 sb.append("hello world"); System.out.println(sb.capacity()); //16 sb.append("Welcome"); System.out.println(sb.capacity()); //34 } }

2). StringBuffer sb=new StringBuffer(int initialcapacity);

 It creates an empty StringBuffer object with the specified initial capacity.

public class StringBuffer2 { public static void main(String[] args) { StringBuffer sb = new StringBuffer(19); System.out.println(sb.capacity()); //19 } }

3). StringBuffer sb=new StringBuffer(String s); 

 It creates an equivalent StringBuffer object for the given String with capacity = s.length()+16;.

public class StringBuffer3 { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Hello World"); System.out.println(sb.capacity()); //27 } } }

4). StringBuffer (CharSequence seq); 

 It Constructs a StringBuffer that contains the same characters as the specified CharSequence.

Important methods of StringBuffer :

1). public int length();


It returns the number of characters present in the StringBuffer.

StringBuffer sb=new StringBuffer("Hello World"); System.out.println(sb.length());//11

2). public int capacity();


It returns the total no of characters StringBuffer can accommodate(hold).

StringBuffer sb=new StringBuffer("Hello World"); System.out.println(sb.capacity());//27

3). public char charAt(int index);
It returns the character located at the specified index.

public class StringBuffer4 { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Hello World Welcome"); System.out.println(sb.length()); //19 System.out.println(sb.capacity()); //35 System.out.println(sb.charAt(15)); //c System.out.println(sb.charAt(30)); //Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 30 } } }

4). public void setCharAt(int index, char ch);
It is used to replace the character locating at a specified index with the provided character.

public class StringBuffer5 { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Hello World Welcome Sara"); System.out.println(sb); sb.setCharAt(20, 'T'); System.out.println(sb); } } Output: Hello World Welcome Sara Hello World Welcome Tara

5). public StringBuffer append(String s);
This method will concatenate the string representation of any type of data to the end of the StringBuffer object. The append() method has several overloaded forms..

public StringBuffer append(String s); public StringBuffer append(int i); public StringBuffer append(long l); public StringBuffer append(boolean b); public StringBuffer append(double d); public StringBuffer append(float f); public StringBuffer append(int index, Object o);

public class StringBuffer5 { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Sara"); System.out.println(sb); //Sara sb.setCharAt(0, 'T'); System.out.println(sb); //Tara } }

6). insert()
This method inserts one string into another string.
append() method has several overloaded forms.

[
public StringBuffer insert(int index,String s); public StringBuffer insert(int index,int i); public StringBuffer insert(int index,long l); public StringBuffer insert(int index,double d); public StringBuffer insert(int index,boolean b); public StringBuffer insert(int index,float f); public StringBuffer insert(int index, Object o);

]
public class StringBuffer6 { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Hello World Welcome to !"); System.out.println(sb); //Hello World Welcome to ! sb.insert(7, "xyz"); sb.insert(26, "2021"); System.out.println(sb); //Hello Wxyzorld Welcome to 2021! } }

7). public StringBuffer delete(int begin,int end);
It is used to delete characters from begin index to the end n-1 index.

8). public StringBuffer deleteCharAt(int index);
It is used to delete the character locating at the specified index.

public class StringBuffer7 { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Hello World Welcome to 2021!"); System.out.println(sb); //Hello World Welcome to 2021! sb.delete(6, 13); System.out.println(sb); // Hello elcome to 2021! sb.deleteCharAt(3); System.out.println(sb); // Helo elcome to 2021! } }

9). public StringBuffer reverse();
It is used to reverse the characters within a StringBuffer object.

public class StringBuffer8 { public static void main(String[] args) { StringBuffer str = new StringBuffer("Sara"); str.reverse(); System.out.println(str); // Sara System.out.println(str); // araS } }

10). public void setLength(int length);
It considers only the specified no of characters and removes all the remaining characters.

public class StringBuffer9 { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Hello World"); System.out.println(sb); //Hello World sb.setLength(5); System.out.println(sb); //Hello } }

11). public void trimToSize();
It is used to deallocate the extra allocated free memory such that capacity and size are equal.

public class StringBuffer10 { public static void main(String[] args) { StringBuffer sb = new StringBuffer(1000); System.out.println(sb.capacity()); //1000 sb.append("Sara"); System.out.println(sb.capacity()); //1000 sb.trimToSize(); System.out.println(sb.capacity()); //4 } }

12). public void ensureCapacity(int initialcapacity);
It is used to increase the capacity dynamically based on our requirement.

public class StringBuffer11 { public static void main(String[] args) { StringBuffer sb = new StringBuffer(); System.out.println(sb.capacity()); //16 sb.ensureCapacity(1000); System.out.println(sb.capacity()); //1000 } }

Every method present in StringBuffer is declared as synchronized hence at a time only one thread is allowed to operate on the StringBuffer object due to this, the waiting time of the threads will be increased and effects performance of the system. 

 To overcome this problem sun people introduced the StringBuilder concept in 1.5v.

StringBuffer StringBuilder
Introduced in 1.0 version. Introduced in 1.5 versions.
Every method present in StringBuffer is synchronized. No method present in StringBuilder is synchronized.
At a time only one thread is allowed to operate on the StringBuffer object hence StringBuffer object is Thread safe. At a time Multiple Threads are allowed to operate simultaneously on the StringBuilder object hence StringBuilder is not Thread safe
It increases the waiting time of the Thread and hence relatively performance is low. Threads are not required to wait and hence relatively performance is high.

Post/Questions related to StringBuffer in Java


StringBuilder in Java with Examples
Java adding New Line in a String
Java String split() method Examples
String lastIndexOf() method examples in Java
String indexOf() method example in Java
String array in Java
How to check if an enum contains String

In this article, we have seen StringBuffer in Java with Examples