Next page | Contents page |

java.lang.StringBuffer

If you want to manipulate text within a String you should first convert it to a StringBuffer, to avoid a lot of string creation and destruction on the heap. StringBuffers provide more methods suitable for text editing.

	StringBuffer sb = new StringBuffer ("Java 6");
	sb.append (" Standard Edition");

Afterwards convert back to String:

	String s = sb.toString ();

toString () is another method which all objects have but when you define a new class you will generally have to define what toString () does (how to do this comes later).

Java 5 has introduced java.lang.StringBuilder which is faster but not thread-safe (we will see what that means later too).

The most useful methods of StringBuffer

StringBuffer append (String s);
char charAt (int index);
StringBuffer delete (int start, int end);
StringBuffer deleteCharAt (int index);
StringBuffer insert (int offset, String s);
int length ();
StringBuffer replace(int start, int end, String s);
StringBuffer reverse ();
String substring (int start, int end);
String toString ();

As with String, several of these methods have overloaded variants with different parameters - see the API doc

Many StringBuffer methods return a reference to the modified StringBuffer object. This is so that operations can be chained. What does the following produce?

	public class X
	{
	  public static void main (String [] args)
	  {
		StringBuffer sb1 = new StringBuffer ("abc");
		sb1.append ("def");      // NB
		StringBuffer sb2 = sb1.append ("ghi");
		System.out.println (sb1.toString () + ", " + sb2.toString ());
	  }
	}

NB: This also illustrates that you do not have to use a returned value by assigning it to anything.

Next page | Contents page |