StringBuffer, StringBuilder

StringBuffer

A buffered representation of a string of characters.

For mutable strings, StringBuffer is more efficient, in terms of performance and memory management.

It is thread-safe. It has several utility methods to manipulate strings.

Where data is not shared among multiple threads, StringBuilder is used. It is modelled in exactly the same way; one can be replaced by the other.

Constructors
– Default:
StringBuffer buffer = new StringBuffer();
– With initial buffer capacity in bytes:
StringBuffer buffer = new StringBuffer(512);
– With literal string:
StringBuffer buffer = new StringBuffer(“a string of characters”);
– With a String object:
String text = “hello, java”;
StringBuffer buffer = new StringBuffer(text);

Methods
append:
adds text to the end of the buffer (eturns the buffer so that the method can be chained)
StringBuffer buffer = new StringBuffer();
buffer.append(“hello”).append(” java,”).append(123);

The append method is overloaded too; it can accept any kind of primitive data type and objects for which toString() has been defined.

insert: like append, it is overloaded; inserts any primitive type at specified​ location

replace(int startChar, int endChar, String chars)

Example

public class BufferDemo
{
	public static void main (String[] args) {
		StringBuffer buffer = new StringBuffer("gable");
buffer.insert(2,'m');
buffer.append("r");
String output = buffer.toString();   // contains gambler

System.out.println(output);
buffer.replace(0,1, "scr");
output = buffer.toString();   // contains scrambler
	
	System.out.println(output);
	}
		
}

StringBuffer is converted back to String using the toString() method.

Advertisements

Author: Anand Betanabhotla

Corporate Trainer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s