Open In App

StringBuffer ensureCapacity() method in Java with Examples

Last Updated : 17 Dec, 2025
Comments
Improve
Suggest changes
9 Likes
Like
Report

The ensureCapacity() method of the StringBuffer class ensures that the buffer has at least the specified minimum capacity. This helps improve performance by reducing the number of internal memory reallocations when appending data.

Syntax:

public void ensureCapacity(int minimumCapacity)

  • Parameters: minimumCapacity, the minimum desired capacity
  • Return Value: This method does not return anything

How ensureCapacity() works internally

  • If current capacity ≥ minCapacity -> no change
  • Else new capacity = (oldCapacity × 2) + 2
  • If minCapacity > calculated value -> new capacity = minCapacity
  • If minCapacity < 0 -> no action

Example 1: Default StringBuffer Capacity

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

        // Create a StringBuffer object
        StringBuffer str = new StringBuffer();

        // Print initial capacity
        System.out.println(
            "Before ensureCapacity method capacity = "
            + str.capacity());

        // Ensure minimum capacity
        str.ensureCapacity(18);

        // Print updated capacity
        System.out.println(
            "After ensureCapacity method capacity = "
            + str.capacity());
    }
}

Output
Before ensureCapacity method capacity = 16
After ensureCapacity method capacity = 34

Explanation

  • Default capacity = 16
  • Required capacity = 18
  • Calculated new capacity = (16 × 2) + 2 = 34
  • Since 34 ≥ 18, capacity becomes 34

Example 2: StringBuffer with Initial Content

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

        // Create a StringBuffer with initial content
        StringBuffer str = new StringBuffer("Geeks For Geeks");

        // Print initial capacity
        System.out.println(
            "Before ensureCapacity method capacity = "
            + str.capacity());

        // Ensure minimum capacity
        str.ensureCapacity(42);

        // Print updated capacity
        System.out.println(
            "After ensureCapacity method capacity = "
            + str.capacity());
    }
}

Output
Before ensureCapacity method capacity = 31
After ensureCapacity method capacity = 64

Explanation

  • Initial string length = 15
  • Initial capacity = 15 + 16 = 31
  • Required capacity = 42
  • Calculated capacity = (31 × 2) + 2 = 64
  • Since 64 ≥ 42, capacity becomes 64

Explore