3

I understand StringBuffer uses the fields 'value' and 'count' which StringBuffer inherits from AbstractStringBuilder. The constructor StringBuffer() for example calls on AbstractStringBuilder(int capacity) to create a 16-Bit-array using super(16). So far so good for how to set 'value' but how or in which method is 'count' set/initialized/determined?

1 Answers1

1

count is initialized to 0, since it represents the number of characters contained in the StringBuffer. Appending characters to the StringBuffer increments the count.

For example, appending a single char increments the count by 1 :

public AbstractStringBuilder append(char c) {
  int newCount = count + 1;
  if (newCount > value.length)
    expandCapacity(newCount);
  value[count++] = c; // count is incremented
  return this;
}
Eran
  • 387,369
  • 54
  • 702
  • 768