I tried the constructors of the StringBuffer class in Java but I was confused with the working of StringBuffer(int initial) constructor.
I know that it gives an initial capacity to the buffer but I have a doubt that, when the initial capacity provided is actually less than the length of the object, how does the capacity increase in such case?
I tried two cases where in first one:
StringBuffer str = new StringBuffer(11);
str.append("Hello World!");
System.out.println(str.length() + " " + str.capacity()); //prints 12 24
that is the capacity becomes twice as that of the length of the string.
and in second one:
StringBuffer str = new StringBuffer(10);
str.append("Hello World!");
System.out.println(str.length() + " " + str.capacity()); //prints 12 22
that is the capacity becomes length + initial buffer capacity
So why such different increase of Buffer size. Initial capacity is less than the string length in both the cases so either it should double to the length in both cases that is becomes 24 or it adds up to the initial buffer that is becomes 23 in the first case and 22 in the second. I read the documentation too and various other blogs but all I could find is the basic use of the constructors and functions of StringBuffer class.
Please help me out. Thank you.
Please refer to the source code of StringBuffer and AbstractStringBuilder:
private int newCapacity(int minCapacity) {
// overflow-conscious code
int newCapacity = (value.length << 1) + 2;
if (newCapacity - minCapacity < 0) {
newCapacity = minCapacity;
}
return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)
? hugeCapacity(minCapacity)
: newCapacity;
}
Please go through these codes and you will get it
For the first block, initial value.length
= 11, and (value.length << 1) + 2
= 24;
For the secondblock, initial value.length
= 10, and (value.length << 1) + 2
= 22;