The above code prints the following when I run it:
The initial capacity of a StringBuilder is 16 unless you specify otherwise. And the length starts empty. The capacity only increases as needed so it doesn't change in this example.
Can you show the code you used to test? And what JDK you are using? I ran it with Java 8 on Mac.
Campbell Ritchie wrote:Where do the 0 and 4 come from? Are you printing the length as well? Those figures suggest the capacity does not increase from 16 to 20.
Edited. I decided to add the length after pasting the code here. Yes, my run suggests the capacity doesn't increase from 16 to 20. I'd be surprised if it did. I would expect capacity jumps to be bigger than that!
With a constructor that initializes to a String: capacity is size + 16
When appending: it only extends the capacity if the new length would exceed it.
When it DOES need to extend the capacity, it does so by taking the current size of the StringBuilder +1 and multiplying that by 2. If that's not enough, then it expands to exactly the amount of space needed.
Given the example from your post: I find it very likely that you were constructing a StringBuilder with "abcd" which would give a capacity of 20, not appending it.
Luckily you don't really need to worry about any of this. The only time I would explicitly set the capacity of a StringBuilder is if I'm going to create and use them like, thousands of times in a loop, or read in a file line-by-line that has 10,000 lines or something; then the performance might be significant.
To 32? That is what I would expect, too.
Jeanne Boyarsky wrote:. . . I would expect capacity jumps to be bigger than that!
OP: Why not go through the source code and see whether you can verify that sort of increase. The fact that ZG has already done that and is about to get a cow is no excuse for not doing it yourself