• August 28, 2014
  • Core Java
  • Comments Off on ensureCapacity(int minCapacity) StringBuilder method in java

ensureCapacity(int minCapacity) StringBuilder method in java

ensureCapacity(int minCapacity): ensures that the capacity is at least equal to the specified minimum.

Syntax: public void ensureCapacity(int minCapacity).

Note:
1. If current capacity is greater than the argument there will be no change in the current capacity.
2. If current capacity is less than the argument there will be change in the current capacity using below rule.
newcapacity = (oldcapacity*2) + 2.

Example:

StringBufferEnsureCapacityExample.java

/**
 * This program is used to show the use of ensureCapacity() method.
 * @author javawithease
 */
class TestStringBuilder{
	StringBuilder sb = new StringBuilder();
 
	/**
	 * This method is used to show the 
         * use of ensureCapacity() method.
	 * @author javawithease
	 */
	public void ensureCapacityTest(){
		//default capacity.
		System.out.println(sb.capacity());
 
		sb.append("Hello ");
		//current capacity 16.
		System.out.println(sb.capacity());
 
		sb.append("www.javawithease.com");
		//current capacity (16*2)+2=34 i.e (oldcapacity*2)+2.  
		System.out.println(sb.capacity());
 
		sb.ensureCapacity(10);
		//now no change in capacity because 
                //minimum is already set to 34. 
		System.out.println(sb.capacity());  
 
		sb.ensureCapacity(50);
		//now (34*2)+2 = 70 as 50 is greater than 34.
		System.out.println(sb.capacity());
	}
}
 
public class StringBufferEnsureCapacityExample {
	public static void main(String args[]){
		//creating TestStringBuilder object
		TestStringBuilder obj = new TestStringBuilder();
 
		//method call
		obj.ensureCapacityTest();
	}
}

Output:

16
34
34
70

Download this example.
 
Next Topic: StringTokenizer in java.
Previous Topic: capacity() StringBuilder method in java.

Related Topics:

StringBuilder in java.
append(String str) StringBuilder method in java.
insert(int offset, String str) StringBuilder method in java.
replace(int startIndex, int endIndex, String str) StringBuilder method in java.
delete(int startIndex, int endIndex) StringBuilder method in java.
reverse() StringBuilder method in java.
capacity() StringBuilder method in java.
ensureCapacity(int minCapacity) StringBuilder method in java.
StringTokenizer in java.

 


Comments are closed.