STRING BUFFERS

CONTENTS

1. Introduction
2. Example


1. INTRODUCTION

String objects are immutable. For example a call to String class method toLowerCase() will not alter thecstring that is passed to it but create a new string. We van change individual elements of a string using replace method. We can also, of course assign an entirely new value to a String instance. But what if we wish to vary the size of an existing string by adding or subtracting characters? To do this we need to crearte an instance of the class StringBuffer. A string buffer is like a string except that it is mutable, i.e. we can add to the string.

There are three StringBuffer constructors avaialbale:

STRING BUFFER CONSTRUCTORS
StringBuffer() Constructs a string buffer with no characters in it and an initial capacity of 16 characters.
StringBuffer(int length) Constructs a string buffer with no characters in it and an initial capacity specified by the length argument.
StringBuffer(String str) Constructs a string buffer so that it represents the same sequence of characters as the string argument.

Once an instance of the class StringBuffer has been created we can allow the object to expand or retract as required using the methods supplied in the StringBuffer class. There are two principal types of method to do this:

  1. Append methods adds the string representation of its argument to the StringBuffer object.
  2. Insert methods insert the string representation of its argument into the StringBuffer object at a given offset.


2. EXAMPLE

Consider the method presented in Table 1. Here we illustrate the use of an append and an insert method from the StringBuffer class. The output generated from this code is presented in Table 2.

// STRING BUFFER EXAMPLE APPLICATION
// Frans Coenen
// Froday 1st September 2000
// The University of Liverpool, UK

import java.io.*;

class StringBufEx {

    // ------------------ METHODS ------------------------

    /* MAIN */
    
    public static void main(String[] args) {

        // Ctreat instance of class StringBuffer and output contents
	
	StringBuffer myBuffer = new StringBuffer("Frans");
	System.out.println("1) " + myBuffer);

        // Add to string buffer
	
	myBuffer.append(" Coenen");
	System.out.println("2) " + myBuffer);
	
	// Insert into string buffer at given offset (5)
	
	myBuffer.insert(5," P.");
	System.out.println("3) " + myBuffer); 
        }
    }

Table 1:String buffer illustration

$ java StringBufEx
1) Frans
2) Frans Coenen
3) Frans P. Coenen       

Table 2:Output from code presented in Table 1

String buffers are also usefull where we wish to pass strings to methods where we wish to change the values of the string object.




Created and maintained by Frans Coenen. Last updated 01 September 2000