Open In App

Java ensureCapacity(int minimumCapacity) Method

Last Updated : 10 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Share
1 Like
Like
Report

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.


Output
Default Capacity: 16
Capacity after ensuring space for 50 characters: 50

Syntax of ensureCapacity() Method

void ensureCapacity(int minimumCapacity)

  • Parameter: minimumCapacity: The minimum capacity that the buffer should have.
  • Return Type: This method does not return any value; it modifies the capacity of the buffer.

Example 2: The below Java program demonstrates how the ensureCapacity() method increases the buffer capacity to ensure it can hold at least 30 characters.


Output
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.


Output
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.


Output
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.


Output
Current Capacity: 16
Capacity after ensuring space for 100 characters: 100

Article Tags :
Practice Tags :

Similar Reads