• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

StringBuffer

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This question relates to capacity of StringBuffers. Pl see the follwing code:
class SBdemo{
public static void main(String[]args){

StringBuffer sb2 = new StringBuffer();
System.out.println("sb2 Cap= " +sb2.capacity());
int b = 17;//Set
sb2.ensureCapacity(b);
System.out.println("sb2 length= " +sb2.length());
System.out.println("sb2 Cap= " +sb2.capacity());//Get
}
}
---
Putting b=1 gives 16 at //Get(that's OK). Putting b=17(or anything till 34 gives 34 at //Get(??).
 
ARS Kumar
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Test
This is the explanation of ensureCapacity
public void ensureCapacity(int minimumCapacity)
Ensures that the capacity of the buffer is at least equal to the specified minimum. If the current capacity of this string buffer is less than the argument, then a new internal buffer is allocated with greater capacity. The new capacity is the larger of:

The minimumCapacity argument.
Twice the old capacity, plus 2.

If the minimumCapacity argument is nonpositive, this method takes no action and simply returns.
Parameters:
minimumCapacity - the minimum desired capacity.
When we apply that to your code, the current capacity being 16 whatever we give as minimumCapacity which is less than or equal to 16 the new capacity() return value will be 16 only.
But when we give anything more than 16 to minimumCapacity then the capacity() return value will be that value.
Thanks
ARS Kumar.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic