When I run this code:
StringBuffer name = new StringBuffer("stackoverflow.com");
System.out.println("Length: " + name.length() + ", capacity: " + name.capacity());
it gives output:
Length: 17, capacity: 33
Obvious length is related to number of characters in string, but I am not sure what capacity is? Is that number of characters that StringBuffer can hold before reallocating space?
Yes, it's exactly that. You can think of
StringBuffer
as being a bit like aVector<char>
in that respect (except obviously you can't usechar
as a type argument in Java...)