Khushit Shah
Khushit Shah

Reputation: 555

Unknown behaviour of StringBuffer.append()

Weird behaviour of StringBuffer.append(): javatpoint states:

If the number of the character increases from its current capacity, it > increases the capacity by (oldcapacity*2)+2.

It can be demonstrated by following code:

class test {
        public static void main(String[] args) {
                StringBuffer sb = new StringBuffer();

                sb.append("abcdef"); // 16;
                System.out.println(sb.capacity());

                sb.append("1234561711"); // 34
                System.out.println(sb.capacity()); // 34
        }
}

But, it shows weird behaviour in following code:

class test {
        public static void main(String[] args) {
                StringBuffer sb = new StringBuffer();

                sb.append("abcdef"); // 16;
                System.out.println(sb.capacity());

                sb.append("12345617111111111111111111111111111111"); // 44 total 44 character in sb, so capacity should be 70 as it goes from 16, 34, 70, 142 etc.
                System.out.println(sb.capacity()); // 34
        }
}

if we use two append with above characters the capacity will be 70! So, I think only one limit breaks in one append()

Upvotes: 0

Views: 105

Answers (1)

Eran
Eran

Reputation: 393781

The logic of StringBuffer's ensureCapacity is stated in the Javadoc:

void java.lang.AbstractStringBuilder.ensureCapacity(int minimumCapacity)

Ensures that the capacity is at least equal to the specified minimum.If the current capacity is less than the argument, then a new internal array is allocated with greater capacity. The new capacity is the larger of:

• The minimumCapacity argument.

• Twice the old capacity, plus 2.

In your second snippet, 44 (which is the minimum required capacity, since after the second append there will be 44 characters in the StringBuffer) is larger than twice the old capacity, plus 2 (which is 34). Hence the new capacity is 44.

Upvotes: 8

Related Questions