File APIs for Java Developers Manipulate DOC, XLS, PPT, PDF and many others from your application. http://aspose.com/file-tools
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login Win a copy of Head First Android this week in the Android forum!

# StringBuffer

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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

Joined: May 22, 2000
Posts: 108
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.

ARS Kumar, Sun Certified Programmer for Java 2 Platform
http://www.automatedsqa.com/

I agree. Here's the link: http://aspose.com/file-tools

subject: StringBuffer