StringBuffer capacity vs ensureCapacity and trimtoSize()

package com.me.practice;

public class StringBufferClass {
public static void main(String[] args) {

//By default it’s 0
StringBuffer stringBuffer=new StringBuffer();

//By default it’s 16
System.out.println(stringBuffer.capacity());

//Now appending “xxxx”
stringBuffer.append(“madhu”);

//Capacity won’t change if length < default capacity
System.out.println(stringBuffer.capacity());
System.out.println(stringBuffer.length());

//Capacity will change if length > default capacity
stringBuffer.append(“madhugggggggggggggggggggggggg”);
System.out.println(stringBuffer.capacity());
System.out.println(stringBuffer.length());

//Capacity won’t change if ensureCapacity < current capacity
stringBuffer.ensureCapacity(23);
System.out.println(stringBuffer.capacity());
System.out.println(stringBuffer.length());

//Capacity will change if ensureCapacity > current capacity
stringBuffer.ensureCapacity(123);
System.out.println(stringBuffer.capacity());
System.out.println(stringBuffer.length());

//Capacity will reduce to actual size
stringBuffer.trimToSize();
System.out.println(stringBuffer.capacity());

}
}

 

16
16
5
34
34
34
34
123
34
34

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s