VOOZH about

URL: https://www.geeksforgeeks.org/java/stringbuffer-ensurecapacity-method-in-java-with-examples/

⇱ StringBuffer ensureCapacity() method in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

StringBuffer ensureCapacity() method in Java with Examples

Last Updated : 17 Dec, 2025

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


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


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
Comment