3

I was looking through the source code of this class and I start from append method that is called by StringBUffer.append();

public AbstractStringBuilder append(String str) { if (str == null) str = "null"; int len = str.length(); if (len == 0) return this; int newCount = count + len; if (newCount > value.length) expandCapacity(newCount); // newcount is the new volumn of a char array str.getChars(0, len, value, count); count = newCount; return this; } 

Then I went deeper into enpandCapacity method

void expandCapacity(int minimumCapacity) { int newCapacity = (value.length + 1) * 2; //here value is a char array if (newCapacity < 0) { // Why is newCapacity less than 0? // Is that possible? When it will be possible? newCapacity = Integer.MAX_VALUE; } else if (minimumCapacity > newCapacity) { newCapacity = minimumCapacity; } value = Arrays.copyOf(value, newCapacity); } 

Why is newCapacity less than 0? Is that possible? When it will be possible?

2
  • It's called arithmetic overflow. Signed integers in Java overflow such that MAX_VALUE + 1 == MIN_VALUE Commented Sep 5, 2012 at 3:21
  • Take for example Integer.MAX_VALUE * 2, which evaluates to -2. Commented Sep 5, 2012 at 3:24

1 Answer 1

3

Yes; signed integers can become negative once the max value of the int type (2^31 - 1) is exceeded. If you take a look, they are essentially capping the capacity at Integer.MAX_VALUE. Similar type of question here.

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

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.