jQuery in Action, 3rd edition
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes StringBuffer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "StringBuffer" Watch "StringBuffer" New topic


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
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.
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.
ARS Kumar.

ARS Kumar, Sun Certified Programmer for Java 2 Platform
I agree. Here's the link: http://aspose.com/file-tools
subject: StringBuffer
It's not a secret anymore!