I was trying to figure out when to use or why capacity()
method is different from length()
method of StringBuilder
or StringBuffer
classes.
I have searched on Stack Overflow and managed to come up with this answer, but I didn't understand its distinction with length()
method. I have visited this website also but this helped me even less.
StringBuilder
is for building up text. Internally, it uses an array of characters to hold the text you add to it. capacity
is the size of the array. length
is how much of that array is currently filled by text that should be used. So with:
StringBuilder sb = new StringBuilder(1000);
sb.append("testing");
capacity()
is 1000 (there's room for 1000 characters before the internal array needs to be replaced with a larger one), and length()
is 7 (there are seven meaningful characters in the array).
The capacity is important because if you try to add more text to the StringBuilder
than it has capacity for, it has to allocate a new, larger buffer and copy the content to it, which has memory use and performance implications*. For instance, the default capacity of a StringBuilder
is currently 16 characters (it isn't documented and could change), so:
StringBuilder sb = new StringBuilder();
sb.append("Singing:");
sb.append("I am the very model of a modern Major General");
...creates a StringBuilder
with a char[16]
, copies "Singing:"
into that array, and then has to create a new array and copy the contents to it before it can add the second string, because it doesn't have enough room to add the second string.
* (whether either matters depends on what the code is doing)