Home | | Web Programming | StringBuffer - Java

Chapter: Java The Complete Reference : The Java Library : String Handling

StringBuffer - Java

StringBuffer supports a modifiable string. As you know, String represents fixed-length, immutable character sequences.

StringBuffer

 

StringBuffer supports a modifiable string. As you know, String represents fixed-length, immutable character sequences. In contrast, StringBuffer represents growable and writable character sequences. StringBuffer may have characters and substrings inserted in the middle or appended to the end. StringBuffer will automatically grow to make room for such additions and often has more characters preallocated than are actually needed, to allow room for growth.

 

StringBuffer Constructors

 

StringBuffer defines these four constructors:

 

StringBuffer( ) StringBuffer(int size) StringBuffer(String str)

StringBuffer(CharSequence chars)

 

The default constructor (the one with no parameters) reserves room for 16 characters without reallocation. The second version accepts an integer argument that explicitly sets the size of the buffer. The third version accepts a String argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation. StringBuffer allocates room for 16 additional characters when no specific buffer length is requested, because reallocation is a costly process in terms of time. Also, frequent reallocations can fragment memory. By allocating room for a few extra characters, StringBuffer reduces the number of reallocations that take place. The fourth constructor creates an object that contains the character sequence contained in chars and reserves room for 16 more characters.

length( ) and capacity( )

 

The current length of a StringBuffer can be found via the length( ) method, while the total allocated capacity can be found through the capacity( ) method. They have the following general forms:

 

int length( ) int capacity( )

 

Here is an example:

 

// StringBuffer length vs. capacity.

class StringBufferDemo {

 

public static void main(String args[]) { StringBuffer sb = new StringBuffer("Hello");

 

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

}

 

}

Here is the output of this program, which shows how StringBuffer reserves extra space for additional manipulations:

 

buffer = Hello length = 5 capacity = 21

 

Since sb is initialized with the string "Hello" when it is created, its length is 5. Its capacity is 21 because room for 16 additional characters is automatically added.

 

ensureCapacity( )

 

If you want to preallocate room for a certain number of characters after a StringBuffer has been constructed, you can use ensureCapacity( ) to set the size of the buffer. This is useful if you know in advance that you will be appending a large number of small strings to a

StringBuffer. ensureCapacity( ) has this general form:

 

void ensureCapacity(int minCapacity)

 

Here, minCapacity specifies the minimum size of the buffer. (A buffer larger than minCapacity may be allocated for reasons of efficiency.)

 

setLength( )

 

To set the length of the string within a StringBuffer object, use setLength( ). Its general form is shown here:

 

void setLength(int len)

 

Here, len specifies the length of the string. This value must be nonnegative.

When you increase the size of the string, null characters are added to the end. If you call setLength( ) with a value less than the current value returned by length( ), then the characters stored beyond the new length will be lost. The setCharAtDemo sample program in the following section uses setLength( ) to shorten a StringBuffer.

 

charAt( ) and setCharAt( )

 

The value of a single character can be obtained from a StringBuffer via the charAt( ) method. You can set the value of a character within a StringBuffer using setCharAt( ). Their general forms are shown here:

 

char charAt(int where)

 

void setCharAt(int where, char ch)

 

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

The following example demonstrates charAt( ) and setCharAt( ):

 

// Demonstrate charAt() and setCharAt().

class setCharAtDemo {

 

public static void main(String args[]) { StringBuffer sb = new StringBuffer("Hello"); System.out.println("buffer before = " + sb);

 

System.out.println("charAt(1) before = " + sb.charAt(1));

 

sb.setCharAt(1, 'i'); sb.setLength(2);

 

System.out.println("buffer after = " + sb); System.out.println("charAt(1) after = " + sb.charAt(1));

 

}

 

}

 

Here is the output generated by this program:

 

buffer before = Hello

charAt(1) before = e

buffer after = Hi

charAt(1) after = i

 

getChars( )

 

To copy a substring of a StringBuffer into an array, use the getChars( ) method. It has this general form:

 

void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)

 

Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd specifies an index that is one past the end of the desired substring. This means that the substring contains the characters from sourceStart through sourceEnd–1. The array that will receive the characters is specified by target. The index within target at which the substring will be copied is passed in targetStart. Care must be taken to assure that the target array is large enough to hold the number of characters in the specified substring.

append( )

The append( ) method concatenates the string representation of any other type of data to the end of the invoking StringBuffer object. It has several overloaded versions. Here are a few of its forms:

 

StringBuffer append(String str) StringBuffer append(int num) StringBuffer append(Object obj)

 

The string representation of each parameter is obtained, often by calling String.valueOf( ). The result is appended to the current StringBuffer object. The buffer itself is returned by each version of append( ). This allows subsequent calls to be chained together, as shown in the following example:

 

 

// Demonstrate append().

class appendDemo {

 

public static void main(String args[]) { String s;

 

int a = 42;

 

StringBuffer sb = new StringBuffer(40);

 

s = sb.append("a = ").append(a).append("!").toString(); System.out.println(s);

 

}

 

}

The output of this example is shown here:

 

a = 42!

 

insert( )

 

The insert( ) method inserts one string into another. It is overloaded to accept values of all the primitive types, plus Strings, Objects, and CharSequences. Like append( ), it obtains the string representation of the value it is called with. This string is then inserted into the invoking StringBuffer object. These are a few of its forms:

 

StringBuffer insert(int index, String str) StringBuffer insert(int index, char ch) StringBuffer insert(int index, Object obj)

 

Here, index specifies the index at which point the string will be inserted into the invoking

 

StringBuffer object.

 

The following sample program inserts "like" between "I" and "Java":

 

// Demonstrate insert().

class insertDemo {

 

public static void main(String args[]) { StringBuffer sb = new StringBuffer("I Java!");

 

sb.insert(2, "like "); System.out.println(sb);

 

}

 

}

 

The output of this example is shown here:

 

I like Java!

 

reverse( )

 

You can reverse the characters within a StringBuffer object using reverse( ), shown here: StringBuffer reverse( )

This method returns the reverse of the object on which it was called. The following program demonstrates reverse( ):

 

// Using reverse() to reverse a StringBuffer.

class ReverseDemo {

 

public static void main(String args[]) { StringBuffer s = new StringBuffer("abcdef");

 

System.out.println(s);

 

s.reverse();

 

System.out.println(s);

 

}

 

}

 

Here is the output produced by the program:

 

abcdef fedcba

 

delete( ) and deleteCharAt( )

 

You can delete characters within a StringBuffer by using the methods delete( ) and deleteCharAt( ). These methods are shown here:

 

StringBuffer delete(int startIndex, int endIndex) StringBuffer deleteCharAt(int loc)

 

The delete( ) method deletes a sequence of characters from the invoking object. Here, startIndex specifies the index of the first character to remove, and endIndex specifies an index one past the last character to remove. Thus, the substring deleted runs from startIndex to endIndex–1. The resulting StringBuffer object is returned.

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

Here is a program that demonstrates the delete( ) and deleteCharAt( ) methods:

 

// Demonstrate delete() and deleteCharAt()

class deleteDemo {

 

public static void main(String args[]) {

 

StringBuffer sb = new StringBuffer("This is a test.");

sb.delete(4, 7); System.out.println("After delete: " + sb);

 

sb.deleteCharAt(0);

 

System.out.println("After deleteCharAt: " + sb);

 

}

 

}

 

The following output is produced:

 

After delete: This a test.

 

After deleteCharAt: his a test.

 

replace( )

 

You can replace one set of characters with another set inside a StringBuffer object by calling replace( ). Its signature is shown here:

 

StringBuffer replace(int startIndex, int endIndex, String str)

 

The substring being replaced is specified by the indexes startIndex and endIndex. Thus, the substring at startIndex through endIndex–1 is replaced. The replacement string is passed in str. The resulting StringBuffer object is returned.

 

The following program demonstrates replace( ):

 

// Demonstrate replace()

class replaceDemo {

public static void main(String args[]) {

 

StringBuffer sb = new StringBuffer("This is a test.");

 

sb.replace(5, 7, "was"); System.out.println("After replace: " + sb);

 

}

 

}

 

Here is the output:

 

After replace: This was a test.

 

substring( )

 

You can obtain a portion of a StringBuffer by calling substring( ). It has the following two forms:

 

String substring(int startIndex)

 

String substring(int startIndex, int endIndex)

The first form returns the substring that starts at startIndex and runs to the end of the invoking StringBuffer object. The second form returns the substring that starts at startIndex and runs through endIndex–1. These methods work just like those defined for String that were described earlier.

Additional StringBuffer Methods

In addition to those methods just described, StringBuffer supplies several others, including those summarized in the following table:




The following program demonstrates indexOf( ) and lastIndexOf( ):

 

class IndexOfDemo {

 

public static void main(String args[]) { StringBuffer sb = new StringBuffer("one two one"); int i;

 

i = sb.indexOf("one"); System.out.println("First index: " + i);

 

i = sb.lastIndexOf("one"); System.out.println("Last index: " + i);

 

}

 

}

The output is shown here:

 

First index: 0

 

Last index: 8



StringBuilder

 

Introduced by JDK 5, StringBuilder is a relatively recent addition to Java’s string handling capabilities. StringBuilder is similar to StringBuffer except for one important difference: it is not synchronized, which means that it is not thread-safe. The advantage of StringBuilder is faster performance. However, in cases in which a mutable string will be accessed by multiple threads, and no external synchronization is employed, you must use StringBuffer rather than StringBuilder.



Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Java The Complete Reference : The Java Library : String Handling : StringBuffer - Java |


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.