0

My question is why after inserting 12 letters 'sb' capacity changes to 34? Why it remains 16 till 11 letters?

How is capacity concept working out here?

StringBuffer sb=new StringBuffer();  
System.out.println(sb.capacity());//default 16  
sb.append("Hello");  
System.out.println(sb.capacity());//now 16  
sb.append("123456789ab");  
System.out.println(sb.capacity());//REMAINS 16
sb.append("123456789abc");
System.out.println(sb.capacity()); // NOW (16*2)+2=34 i.e (oldcapacity*2)+2
Anuj
  • 307
  • 2
  • 14
  • I don't understand your question. Your comments seem to answer your confusion. – Sotirios Delimanolis Jul 05 '17 at 05:23
  • Also, the page you took this code from also explains how the capacity works. – Sotirios Delimanolis Jul 05 '17 at 05:24
  • 3
    @ArvindSasikumar: Because the OP is wrong about how many characters have been inserted. There's the five characters from `"Hello"` _plus_ the eleven characters from "123456789ab" _plus_ the twelve characters in `"123456789abc"`. – Louis Wasserman Jul 05 '17 at 05:33
  • 1
    @LouisWasserman thanks you pointed out correctly "append" OP is increasing length so it should be taken as 5+11=16 and when 5+12=17, that's when capacity gets increased by a set formula. Thanks again. – Anuj Jul 05 '17 at 05:38

0 Answers0