
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Change Default Capacity of StringBuffer Object in Java
In order to change the default capacity of the StringBuffer Object, we use the ensureCapacity() method. When the current capacity is less than the parameter passed, then a new internal array is allocated with greater capacity.
The new capacity is the larger of the minimumCapacity argument and twice the old capacity, plus 2. If the minimum capacity is non positive, then it remains dormant and does not take any action.
Declaration-The java.lang.StringBuffer.ensureCapacity() method is declared as follows−
public void ensureCapacity(int minimumCapacity)
Let us see the working of the ensureCapacity() method
Example
public class Example { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Hello"); System.out.println(sb); System.out.println("Original capacity : "+sb.capacity()); sb.ensureCapacity(29); // the (twice of old capacity + 2) argument is greater System.out.println("New capacity : "+sb.capacity()); System.out.println(); StringBuffer sb1 = new StringBuffer("Hi"); System.out.println(sb1); System.out.println("Original capacity : "+sb1.capacity()); sb1.ensureCapacity(40); // the minimumCapacity argument is greater System.out.println("New capacity : "+sb1.capacity()); } }
Output
Hello Original capacity : 21 New capacity : 44 Hi Original capacity : 18 New capacity : 40
Advertisements