Difference between the StringBuffer’s capacity() and length()

The StringBuffer has internally an array of characters in which it keeps the values of the characters. Each time you try to add more characters than this array’s length, a new, bigger array must be created and the characters must be copied into it. StringBuffer.length() returns the length of string you have stored into the StringBuffer, the value you would normally expect. StringBuffer.capacity() returns the size of that internal array, which means how many characters can that StringBuffer keep without having to allocate a new, bigger array.