ensureCapacity( )

To preallocate room for a certain number of characters after a StringBuffer has been constructed, use ensureCapacity( ) to set the size of the buffer.

ensureCapacity( ) has this general form:


void ensureCapacity(int capacity)

capacity specifies the size of the buffer.


public class Main {
  public static void main(String args[]) {
    StringBuffer sb = new StringBuffer();
    sb.ensureCapacity(100 ); 
    sb.append("java2s.com");
    System.out.println(sb.capacity());
    System.out.println(sb.length());
    System.out.println(sb.toString());
    
  }
}

Output:


100
10
java2s.com
Home 
  Java Book 
    Essential Classes  

StringBuffer:
  1. Create StringBuffer object
  2. append
  3. StringBuffer capacity()
  4. charAt(int index): get the char at specified index
  5. delete(int start, int end) and deleteCharAt(int index)
  6. ensureCapacity( )
  7. getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
  8. indexOf(String str)
  9. lastIndexOf(String str)
  10. StringBuffer length()
  11. Insert(): add data in the middle of a StringBuffer
  12. replace():replace a StringBuffer
  13. StringBuffer reverse()
  14. setCharAt(int index, char ch)
  15. setLength
  16. substring
  17. toString():Convert StringBuffer to String