because stringbuffer internally uses an array and the maximum number of elements an array can accommodate is 2^31-1 if you increment after reaching this it will go to negative and throws the error
Answer from Pavan Kumar on Stack Overflowbecause stringbuffer internally uses an array and the maximum number of elements an array can accommodate is 2^31-1 if you increment after reaching this it will go to negative and throws the error
StringBuffer uses a char[].
In Java an array can be indexed only via an integer which means the highest value the index of the array can be is Integer.MAX_VALUE - 1 (i.e. 2^31 - 1). Which means that the size of an array in Java can not be larger than Integer.MAX_VALUE
Here is what java API for StringBuffer, https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html, says "Every string buffer has a capacity. As long as the length of the character sequence contained in the string buffer does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the internal buffer overflows, it is automatically made larger." Hence if you add more characters, it will increase capacity as needed and grow.
When you created StringBuffer object called theString. Java will allocate you 32 chracter capacity. If length of object exceeds 32 it add more 32 characters so capacity will become 64 likewise. so you will get 32 capacity untill your character lrngth is less than 32