2

According to java doc, I got this idea:

StringBuilder(int length) in java ,creates an empty string Builder with the specified capacity as length.

I tried the code below:

StringBuilder sb = new StringBuilder(9);

But I can append length more than 9.

sb.append("123456789123456789123456789123456789123456789123456789");

What is the meaning of assign this length?

3
  • 4
    It doesn't mean that you cannot put more than 9 characters in the StringBuilder; it just means that it reserves space for 9 characters when you create the StringBuilder. When you put in more characters, it will grow automatically. The capacity is not fixed to what you pass the constructor, it's just the initial capacity. Commented Nov 1, 2017 at 10:15
  • 5
    Why don't you read the javadoc? It says: Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.. The javadoc is your friend. Read it. docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html Commented Nov 1, 2017 at 10:16
  • Tried reading the existing javadoc? Commented Nov 1, 2017 at 10:18

2 Answers 2

2

When you use StringBuilder repeatedly, it re-allocates its buffer each time that it needs to accommodate a longer string. If you know that your target string is going to be of a certain length, you can save on re-allocation by telling StringBuilder the length of your string.

This is going to be the length of the initial allocation; appending under this limit is not going to cause re-allocations. However, StringBuilder would not have a hard limit: going beyond the initial size is allowed.

Sign up to request clarification or add additional context in comments.

Comments

0

The value that you passed in the constructor is the StringBuilder's initial capacity. Its not equal to the length of the string being built by it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.