by Dinesh Thakur

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:

StringBuffer()

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.

Syntax:

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.

Syntax:

void ensureCapacity(int capacity)

Here, capacity specifies the size of the buffer.

setLength()

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

Syntax:

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().

Syntax:

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.

getChars()

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

Syntax:

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..

Syntax:

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

import java.io.*;
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--)
                                    d.append(s.charAt(i));
                        return d.toString();
            }
            public static void main (String args[]) throws IOException
            {
                        BufferedReader k=new BufferedReader(new InputStreamReader(System.in));
                        String p,q;
                        System.out.println("Enter a string");
                        p=k.readLine();
                        q=reverseIt(p);
                        System.out.println("Original String is "+p);
                        System.out.println("Reversed String is "+q);
            }
}

StringBuffer Class in Java Example

Insert()

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.

Syntax:

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");
                        sb.append('!');
                        sb.insert(0,"Beleive");
                                sb.append('\n');
                        sb.append("God is Great");
                        sb.setCharAt(20,'I');
                        String s = sb.toString();
                        System.out.println(s);
            }
}

StringBuffer Class in Java Example

reverse()

 

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

import java.io.*;
class StringReverse
{
            public static void main(String args[])
            {
                        StringBuffer k=new StringBuffer("Hello Java");
                        System.out.println(k);
                        k.reverse();
                        System.out.println(k);
            }
}

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.

Replace()

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

Syntax:

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.

Syntax:

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;
                        p.getChars(7,11,k,0);
                        System.out.println("Original string is "+p);
                        p.delete(4,6);
                        System.out.println("string after deleting a word "+p);
                        p.insert(4,"is");
                        System.out.println("string after inserting a word "+p);
                        p.deleteCharAt(4);
                        System.out.println("string after deleting a character"+p);
                        p.replace(4,5,"always");
                        System.out.println("string after replacing a word is "+p);
                        q=p.charAt(0);
                        System.out.println("the first character of string is "+q);
            }
}

StringBuffer Class in Java Example