I got a StringIndexOutOfBoundsException
for setCharAt(int index, char ch)
:
StringBuilder word = new StringBuilder(4);
for(int i = 0; i < 4; i++)
word.setCharAt(i,'-');
StringBuilder(int capacity)
: Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument.
setCharAt(int index, char ch)
: The character at the specified index is set to ch.
The only thing I can think of is that no memory was allocated, but then what's the point of StringBuilder(int capacity)
?
Just use StringBuilder.append()
The constructor you're using does nothing to put data in the StringBuilder.
It only specifies a practical size for the StringBuilder (which I believe is for performance).
Until you actually put stuff in the StringBuilder, your code will throw Exceptions.
Note that the documentation you've quoted says this explicitly:
"Constructs a string builder with NO CHARACTERS in it..."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With