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:

 * Copyright (c) All Rights Reserved.
public class SimpleStringBuffer {
   private char[] buffer;
   private int capacity;
   private int length;
   public SimpleStringBuffer() {
   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:

See the next section for testing result of this class.

Table of Contents

 About This Book

 JDK - Java Development Kit

 Execution Process, Entry Point, Input and Output

 Primitive Data Types and Literals

 Control Flow Statements

 Bits, Bytes, Bitwise and Shift Operations

 Managing Bit Strings in Byte Arrays

 Reference Data Types and Variables

 Enum Types and Enum Constants

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

 Generic Classes and Parameterized Types

 Generic Methods and Type Inference

 Lambda Expressions and Method References

 Java Modules - Java Package Aggregation

 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

 Assert Statements and -ea" Option

 Annotation Statements and Declarations

 Java Related Terminologies

 Archived Tutorials


 Full Version in PDF/EPUB