Java Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 6.00

SimpleStringBuffer - My Implementation of String Buffer

This section provides a tutorial example on how to implement a simple string buffer class similar to the StringBuffer class included in the java.lang package.

In order to better understand the StringBuffer class, I wrote the following program, SimpleStringBuffer, which implements a really simple string buffer class with only one append() method:

/**
 * SimpleStringBuffer.java
 * Copyright (c) 2003 by Dr. Herong Yang
 */
public class SimpleStringBuffer {
   private char[] buffer; 
   private int capacity;
   private int length;
   public SimpleStringBuffer() {
      this(16);
   }
   public SimpleStringBuffer(int l) {
      capacity = l;
      buffer = new char[capacity];
      length = 0;
   }
   public synchronized SimpleStringBuffer append(String str) {
      String s = str;
      if (s==null) s = "null";
      if (length+s.length()>capacity) {
         int l = Math.max(length+s.length(), 2*capacity);
         char[] b = new char[l];
         for (int i=0; i<length; i++) {
            b[i] = buffer[i];
         }
         buffer = b;
         capacity = l;
      }
      for (int i=0; i<s.length(); i++) {
         buffer[length+i] = s.charAt(i);
      }
      length += s.length();
      return this;
   }
   public String toString() {
      return new String(buffer, 0, length);
   }

Several notes on this class:

  • I used a character array "char[]" as the storage for the string buffer.
  • Two constructor methods are provided: one takes the default buffer capacity of 16 characters, and the other allows the caller to specify a specific capacity.
  • The main method is append(), which appends the specified string to the end of the buffer.
  • If there are not enough free spaces in the buffer to append the specified string, the buffer will be extended with a higher capacity.

See the next section for testing result of this class.

Table of Contents

 About This Book

 Installing JDK 1.4 on Windows 2000

 Installing JDK 1.5 on Windows XP

 Installing JDK 1.6 on Windows XP

 Execution Process, Entry Point, Input and Output

 Bits, Bytes, Bitwise and Shift Operations

 Managing Bit Strings in Byte Arrays

StringBuffer - The String Buffer Class

 StringBuffer Class Properties and Methods

SimpleStringBuffer - My Implementation of String Buffer

 Performance Comparison of String and StringBuffer

 System Properties and Runtime Object Methods

 Execution Threads and Multi-Threading Java Programs

 ThreadGroup Class and "system" ThreadGroup Tree

 Synchronization Technique and Synchronized Code Blocks

 Deadlock Condition Example Programs

 Garbage Collection and the gc() Method

 References

 PDF Printing Version

Dr. Herong Yang, updated in 2008
SimpleStringBuffer - My Implementation of String Buffer