![]() |
VOOZH | about |
In Java, the ensureCapacity(int minimumCapacity) method of the StringBuilder and StringBuffer classes is used to ensure that the buffer has a minimum capacity. If the current capacity is less than the specified minimum, it will increase the capacity to accommodate the required size.
Example 1: The below Java program demonstrates how the ensureCapacity() method makes sure there's enough space to hold a certain number of characters.
Default Capacity: 16 Capacity after ensuring space for 50 characters: 50
void ensureCapacity(int minimumCapacity)
Example 2: The below Java program demonstrates how the ensureCapacity() method increases the buffer capacity to ensure it can hold at least 30 characters.
Default Capacity: 16 Capacity after ensuring space for 30 characters: 34
Example 3: The below Java program demonstrates how the ensureCapacity() ensures the buffer capacity is large enough to hold at least 100 characters.
Capacity after ensuring space for 100 characters: 100
Example 4: The below Java program demonstrates how the ensureCapacity() ensure sufficient capacity for 50 characters while maintaining the existing content.
Current Capacity: 21 Capacity after ensuring space for 50 characters: 50
Example 5: The below Java program demonstrates how the ensureCapacity() ensure the buffer has enough capacity to hold at least 100 characters.
Current Capacity: 16 Capacity after ensuring space for 100 characters: 100