Priyantha
Priyantha

Reputation: 5091

How to use StringBuilder(int length) in Java

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?

Upvotes: 2

Views: 1582

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

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.

Upvotes: 2

Raja Anbazhagan
Raja Anbazhagan

Reputation: 4564

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.

Upvotes: 0

Related Questions