StringBuffer sb = new StringBuffer("Hello World!"); sb.ensureCapacity(50);
StringBuffer sb = new StringBuffer(); sb.append("Hello"); sb.ensureCapacity(20);In this example, the capacity of the StringBuffer is increased to 20 to accommodate more characters. This method can be used when appending long strings to avoid unnecessary memory allocation. The StringBuffer ensureCapacity() method belongs to the java.lang package library.