Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# StringBuffer

Anonymous
Ranch Hand
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
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.