How StringBuilder works internally?

String and StringBuilder, Immutability and Mutability are famous topics and they are discussed around everywhere, but i wondered how StringBuilder had aided advantages over String and StringBuffer.

There are few things that matter.

1. String is immutable, which means each time you try to concatenate or use any method, it creates a new object and returns you the modified object.

2. StringBuffer, is a buffer but its synchronized, and too expensive for memory, so it should be avoided. If you need synchronization You can use locks etc. otherwise.

3. StringBuilder in JSE 1.5 is superior to above two, its mutable, its not synchronized. Its mutable because it does not create String reference each time you try to invoke its methods, i.e. append(), rather it changes. It should be used if your String opperations are larger. Do not use it if you just want to concatenate a String for 3 or 4 times or known number of times.


How StringBuilder Works?

It's Object maintains a buffer to accommodate the concatenation of new data. New data is added to the end of the buffer if room is available; otherwise, a new, larger buffer is allocated, data from the original buffer is copied to the new buffer, then the new data is appended to the new buffer.


Following is the code snippet from AbstractStringBuilder which is super class of StringBuilder.

 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;
}


void expandCapacity(int minimumCapacity) {
int newCapacity = (value.length + 1) * 2;
if (newCapacity <>
newCapacity = Integer.MAX_VALUE;
} else if (minimumCapacity > newCapacity) {
newCapacity = minimumCapacity;
}
value = Arrays.copyOf(value, newCapacity);
}

Comments