by Dinesh Thakur Category: array

StringBuffer represents grow able and write able character sequences. We can modify the StringBuffer object, i.e. we can append more characters or may insert a substring in middle. StringBuffer will automatically grow to make room for such additions and is very flexible to the modifications.

StringBuffer Constructors


StringBuffer defines these three constructors:


It reserves room for 16 characters without reallocation.

StringBuffer(int size)

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

StringBuffer(String str)

It accepts a String argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation.

length( ) and capacity( )

The current length of a StringBuffer can be found by the length() method, while the total allocated capacity can be found through the capacity() method.


int length()

int capacity()

ensureCapacity( )

If we want to preallocate room for a certain number of characters after a StringBuffer has been constructed, we can use ensureCapacity() to set the size of the buffer.


void ensureCapacity(int capacity)

Here, capacity specifies the size of the buffer.


It is used to set the length of the buffer within a StringBuffer object.


void setLength(int len)

Here, len specifies the length of the buffer. This value must be nonnegative. When we increase the size of the buffer, null characters are added to the end of the existing buffer. If we call setLength() with a value less than the current value returned by length(), then the characters stored beyond the new length will be lost.

charAt() and setCharAt( )

A single character can be obtained from a StringBuffer by the charAt() method. We can even set the value of a character within a StringBuffer using setCharAt().


char charAt(int loe}

void setCharAt(int loc, char ch)

loc specifies the location of the character being obtained. For setCharAt(), loc specifies the location of the character being set, and ch specifies the new value of that character. For both methods, loc must be nonnegative and must not specify a location beyond the end of the buffer.


To copy a substring of a StringBuffer into an array, use the getChars() method.


void getChars(int si, int e, char t[ ], int ti)

Here, si specifies the index of the beginning of the substring, and e specifies an index that is one past the end of the desired substring. This means that the substring contains the characters from si through e-l. The array that will receive the characters is specified by t. The index within t at which the substring will be copied is passed in ti.

append( )

The append() method concatenates the string representation of any other type of data to the end of the invoking StringBuffer object..


StringBuffer append(String str)

StringBuffer append(int num)

StringBuffer append(Object obf)

String.valueOf() is called for each parameter to obtain its string representation. The result is appended to the current StringBuffer object. The buffer itself is returned by each version of append().

The append() method is most often called when the + operator is used on String objects. Java automatically changes modifications to a String instance into similar operations on a StringBuffer instance. Thus, a concatenation invokes append() on a StringBuffer object. After the concatenation has been performed, the compiler inserts a call to toString() to turn the modifiable StringBuffer back into a constant String

public class ReversedString
            public static String reverseIt(String s)
                        int i, n;
                        n = s.length();
                        StringBuffer d = new StringBuffer(n);
                        for (i = n - 1; i >= 0; i--)
                        return d.toString();
            public static void main (String args[]) throws IOException
                        BufferedReader k=new BufferedReader(new InputStreamReader(;
                        String p,q;
                        System.out.println("Enter a string");
                        System.out.println("Original String is "+p);
                        System.out.println("Reversed String is "+q);

StringBuffer Class in Java Example


The insert() method inserts one string into another. It is overloaded to accept values of all the simple types, plus Strings and Objects. Like append(), it calls String.valueOf () to obtain the string representation of the value it is called with. This string is then inserted into the invoking StringBuffer object.


StringBuffer insert(int loc, String str)

StringBuffer insert(int loc, char ch)

StringBuffer insert(int loc, Object obj)

Here, loc specifies the location at which point the string will be inserted into the invoking StringBuffer object.

public class StringInsert           
          public static void main(String args[])
                        StringBuffer sb = new StringBuffer(" in ");
                        sb.append("God is Great");
                        String s = sb.toString();

StringBuffer Class in Java Example



We can reverse the characters within a StringBuffer object using reverse()ยท

class StringReverse
            public static void main(String args[])
                        StringBuffer k=new StringBuffer("Hello Java");

StringBuffer Class in Java Example

delete( ) and deleteCharAt( )

StringBuffer delete(int s, int e)

StringBuffer deleteCharAt(int loc)

The delete() method deletes a sequence of characters from the invoking object. Here, s specifies the starting location of the first character to remove, and e specifies location one past the last character to remove. Thus, the substring deleted runs from s to e-l. The resulting StringBuffer object is returned.

The deleteCharAt() method deletes the character at the location specified by loco It returns the resulting StringBuffer object.


It replaces one set of characters with another set inside a StringBuffer object.


StringBuffer replace(int s, int e, String str)

The substring being replaced is specified by the location sand e. Thus, the substring at s through e-l is replaced by str string.

substring( )

It returns a portion of a StringBuffer.


String substring(int s)

String substring(int s, int e)

The first form returns the substring that starts at s and runs to the end of the invoking StringBuffer object. The second form returns the substring that starts at s and runs through e-l.

public class StringBuffer2

            public static void main (String args[])
                        StringBuffer p= new StringBuffer("God is Great");
                        char k[] = new char[20];
                        char q;
                        System.out.println("Original string is "+p);
                        System.out.println("string after deleting a word "+p);
                        System.out.println("string after inserting a word "+p);
                        System.out.println("string after deleting a character"+p);
                        System.out.println("string after replacing a word is "+p);
                        System.out.println("the first character of string is "+q);

StringBuffer Class in Java Example

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles