The implementation of Apache Harmony is based on the AbstractStringBuilder methods for managing add / removes ( StringBuffer extends AbstractStringBuilder ).
AbstractStringBuilder stores a character buffer (ie an array of char s) to hold the current "string". When adding the following string representation of any object to this buffer, it checks to see if the buffer contains enough space, and if there is not enough space in it, it allocates a new character buffer, copies the old buffer, and then adds a new line to this buffer. We can get this from the internal elements of enlargeBuffer :
private void enlargeBuffer(int min) { int newSize = ((value.length >> 1) + value.length) + 2; char[] newData = new char[min > newSize ? min : newSize]; System.arraycopy(value, 0, newData, 0, count); value = newData; shared = false; }
... and this method is called in any add method when the capacity of value (the private member that contains the char buffer) is exceeded:
final void append0(char chars[]) { int newSize = count + chars.length; if (newSize > value.length) { enlargeBuffer(newSize); } System.arraycopy(chars, 0, value, count, chars.length); count = newSize; }
The standard OpenJDK implementation is pretty similar. Again, StringBuffer relies on AbstractStringBuilder :
void expandCapacity(int minimumCapacity) { int newCapacity = (value.length + 1) * 2; if (newCapacity < 0) { newCapacity = Integer.MAX_VALUE; } else if (minimumCapacity > newCapacity) { newCapacity = minimumCapacity; } value = Arrays.copyOf(value, newCapacity); }
Note that Arrays.copyOf copies the array of value characters, filling it with null characters to have a total size of newCapacity , which is basically equivalent to calling new char[...] in the Harmony approach. Again, the expandCapacity method expandCapacity called when there is not enough space to add the following line segment:
public AbstractStringBuilder append(String str) { if (str == null) str = "null"; int len = str.length(); if (len == 0) return this; int newCount = count + len; if (newCount > value.length) expandCapacity(newCount); str.getChars(0, len, value, count); count = newCount; return this; }