StringBuffer in Java Programming Language

Rumman Ansari   Software Engineer   2019-03-30   8147 Share
☰ Table of Contents

Table of Content:


StringBuffer class is used to create a mutable string object i.e its state can be changed after it is created.The StringBuffer class are used when there is a necessity to make a lot of modifications to Strings of characters.

The StringBuilder classe are similar to the String class except that the String class is immutable.

StringBuffer is more flexible than String We can add, insert, or append new contents into StringBuffer objects, whereas the value of a String object is fixed once the string is created.

The StringBuilder class is similar to StringBuffer except that the methods for modifying the buffer in StringBuffer are synchronized, which means that only one task is allowed to execute the methods.Use StringBuffer if the class might be accessed by multiple tasks con- currently.

StringBuffer Constructors

StringBuffer defines these four constructors:

StringBuffer( ) 
StringBuffer(int size) 
StringBuffer(String str) 
StringBuffer(CharSequence chars)

StringBuffer( )

The default constructor with no parameters.

Creates a StringBuffer object with an empty string placed in the buffer initially with a buffer capacity of 16 characters to store.

StringBuffer(int size)

It accepts an integer argument that explicitly sets the size of the buffer.

Creates a StringBuffer object with an empty string placed in the buffer initially with a buffer capacity of initialCapacity.

StringBuffer(String str)

It accepts a String argument that sets the initial contents of the StringBuffer object

Creates a StringBuffer object with string str placed in the buffer initially with a buffer capacity of 16 + str.length().

StringBuffer(CharSequence chars)

This constructor creates an object that contains the character sequence contained in chars.

Creates a StringBuffer object with CharSequence seq placed in the buffer initially with a buffer capacity of 16 + seq.length().

Program

 
class StringBufferDemo {
public static void main(String args[]) {

  StringBuffer sb1 = new StringBuffer();
  StringBuffer sb2 = new StringBuffer(2);
  StringBuffer sb3 = new StringBuffer("Hello");
  StringBuffer sb4 = new StringBuffer('A');

  System.out.println("buffer = " + sb1);
  System.out.println("buffer = " + sb2);
  System.out.println("buffer = " + sb3);
  System.out.println("buffer = " + sb4);

  }
}
 

Output

 buffer =
buffer =
buffer = Hello
buffer =
Press any key to continue . . .
 

Two Important Method capacity() and length()

int length( )
int capacity( )

length()

Returns the number of characters present in the buffer(The current length of a StringBuffer) as an int value. By common sense also you can say, buffer length (number of characters present) cannot be more than the buffer capacity.

capacity()

Returns the buffer storing capacity as an int value. Initially the default constructor creates 16 buffer capacity and increases automatically when the buffer gets filled up with string. Programmer can place extra data in the buffer with append() method.

Let us illustrate the length and capacities through an example.

Program

// StringBuffer length vs. capacity.
class StringBufferDemo {

public static void main(String args[]) {

	StringBuffer strng = new StringBuffer("atnyla");

	System.out.println("buffer = " + strng);
	System.out.println("length = " + strng.length());
	System.out.println("capacity = " + strng.capacity());
 }
}

Output

buffer = atnyla
length = 6
capacity = 22
Press any key to continue . . .

Following example illustrates the usage of 4 types of StringBuffer Constructors.

Program

public class StringBufferDemoAll
{
  public static void main(String args[])
  {
   StringBuffer sb1 = new StringBuffer();
   System.out.println("sb1 length: " + sb1.length());
   // prints 0 as there is not data in the buffer
   System.out.println("sb1 capacity: " + sb1.capacity());
   // prints 16, the default capacity

   StringBuffer sb2 = new StringBuffer(50);
   System.out.println("sb2 length: " + sb2.length());
   // prints 0 as there is not data in the buffer
   System.out.println("sb2 capacity: " + sb2.capacity());
   // prints 50

   String str1 = "hello";
   StringBuffer sb3 = new StringBuffer(str1);
   System.out.println("sb3 length: " + sb3.length());
   // prints 5, the length of hello
   System.out.println("sb3 capacity: " + sb3.capacity());
   // prints 22; str1.length()+16

   CharSequence seq1 = "hello";
   StringBuffer sb4 = new StringBuffer(seq1);
   System.out.println("sb4 length: " + sb4.length());
   // prints 5, the length of hello
   System.out.println("sb4 capacity: " + sb4.capacity());
   // prints 22; str1.length()+16
 }
}

Output

sb1 length: 0
sb1 capacity: 16
sb2 length: 0
sb2 capacity: 50
sb3 length: 5
sb3 capacity: 21
sb4 length: 5
sb4 capacity: 21
Press any key to continue . . .

StringBuffer Methods

Modifier and Type Method and Description
StringBuffer append(boolean b)
Appends the string representation of the boolean argument to the sequence.
StringBuffer append(char c)
Appends the string representation of the char argument to this sequence.
StringBuffer append(char[] str)
Appends the string representation of the char array argument to this sequence.
StringBuffer append(char[] str, int offset, int len)
Appends the string representation of a subarray of the char array argument to this sequence.
StringBuffer append(CharSequence s)
Appends the specified CharSequence to this sequence.
StringBuffer append(CharSequence s, int start, int end)
Appends a subsequence of the specified CharSequence to this sequence.
StringBuffer append(double d)
Appends the string representation of the double argument to this sequence.
StringBuffer append(float f)
Appends the string representation of the float argument to this sequence.
StringBuffer append(int i)
Appends the string representation of the int argument to this sequence.
StringBuffer append(long lng)
Appends the string representation of the long argument to this sequence.
StringBuffer append(Object obj)
Appends the string representation of the Object argument.
StringBuffer append(String str)
Appends the specified string to this character sequence.
StringBuffer append(StringBuffer sb)
Appends the specified StringBuffer to this sequence.
StringBuffer appendCodePoint(int codePoint)
Appends the string representation of the codePoint argument to this sequence.
int capacity()
Returns the current capacity.
char charAt(int index)
Returns the char value in this sequence at the specified index.
int codePointAt(int index)
Returns the character (Unicode code point) at the specified index.
int codePointBefore(int index)
Returns the character (Unicode code point) before the specified index.
int codePointCount(int beginIndex, int endIndex)
Returns the number of Unicode code points in the specified text range of this sequence.
StringBuffer delete(int start, int end)
Removes the characters in a substring of this sequence.
StringBuffer deleteCharAt(int index)
Removes the char at the specified position in this sequence.
void ensureCapacity(int minimumCapacity)
Ensures that the capacity is at least equal to the specified minimum.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Characters are copied from this sequence into the destination character array dst.
int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
StringBuffer insert(int offset, boolean b)
Inserts the string representation of the boolean argument into this sequence.
StringBuffer insert(int offset, char c)
Inserts the string representation of the char argument into this sequence.
StringBuffer insert(int offset, char[] str)
Inserts the string representation of the char array argument into this sequence.
StringBuffer insert(int index, char[] str, int offset, int len)
Inserts the string representation of a subarray of the str array argument into this sequence.
StringBuffer insert(int dstOffset, CharSequence s)
Inserts the specified CharSequence into this sequence.
StringBuffer insert(int dstOffset, CharSequence s, int start, int end)
Inserts a subsequence of the specified CharSequence into this sequence.
StringBuffer insert(int offset, double d)
Inserts the string representation of the double argument into this sequence.
StringBuffer insert(int offset, float f)
Inserts the string representation of the float argument into this sequence.
StringBuffer insert(int offset, int i)
Inserts the string representation of the second int argument into this sequence.
StringBuffer insert(int offset, long l)
Inserts the string representation of the long argument into this sequence.
StringBuffer insert(int offset, Object obj)
Inserts the string representation of the Object argument into this character sequence.
StringBuffer insert(int offset, String str)
Inserts the string into this character sequence.
int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring.
int length()
Returns the length (character count).
int offsetByCodePoints(int index, int codePointOffset)
Returns the index within this sequence that is offset from the given index by codePointOffset code points.
StringBuffer replace(int start, int end, String str)
Replaces the characters in a substring of this sequence with characters in the specified String.
StringBuffer reverse()
Causes this character sequence to be replaced by the reverse of the sequence.
void setCharAt(int index, char ch)
The character at the specified index is set to ch.
void setLength(int newLength)
Sets the length of the character sequence.
CharSequence subSequence(int start, int end)
Returns a new character sequence that is a subsequence of this sequence.
String substring(int start)
Returns a new String that contains a subsequence of characters currently contained in this character sequence.
String substring(int start, int end)
Returns a new String that contains a subsequence of characters currently contained in this sequence.
String toString()
Returns a string representing the data in this sequence.
void trimToSize()
Attempts to reduce storage used for the character sequence.