Java StringBuilder ensureCapacity() Method

The StringBuilder.ensureCapacity() method in Java is used to ensure that the StringBuilder object has a minimum capacity.

Table of Contents

  1. Introduction
  2. ensureCapacity Method Syntax
  3. Examples
    • Ensuring Minimum Capacity
    • Checking Capacity Before and After Ensuring
    • Increasing Capacity
  4. Real-World Use Case
  5. Conclusion

Introduction

The StringBuilder.ensureCapacity() method is a member of the StringBuilder class in Java. It ensures that the StringBuilder has at least the specified minimum capacity. If the current capacity is less than the specified minimum, a new internal buffer is allocated with a larger capacity.

ensureCapacity() Method Syntax

The syntax for the ensureCapacity method is as follows:

public void ensureCapacity(int minimumCapacity)
  • minimumCapacity: The minimum desired capacity for the StringBuilder object.

Examples

Ensuring Minimum Capacity

You can use the ensureCapacity method to set a minimum capacity for the StringBuilder.

Example

public class StringBuilderEnsureCapacityExample {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();

        // Ensure the capacity is at least 50
        sb.ensureCapacity(50);

        // Print the capacity after ensuring
        System.out.println("Capacity after ensuring: " + sb.capacity());
    }
}

Output:

Capacity after ensuring: 50

Checking Capacity Before and After Ensuring

You can check the capacity of the StringBuilder before and after calling the ensureCapacity method to see the difference.

Example

public class StringBuilderEnsureCapacityExample {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();

        // Print initial capacity
        System.out.println("Initial capacity: " + sb.capacity());

        // Ensure the capacity is at least 50
        sb.ensureCapacity(50);

        // Print capacity after ensuring
        System.out.println("Capacity after ensuring: " + sb.capacity());
    }
}

Output:

Initial capacity: 16
Capacity after ensuring: 50

Increasing Capacity

If the current capacity is already greater than or equal to the specified minimum, the ensureCapacity method will not change the capacity.

Example

public class StringBuilderEnsureCapacityExample {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder(100);

        // Print initial capacity
        System.out.println("Initial capacity: " + sb.capacity());

        // Ensure the capacity is at least 50 (no change expected)
        sb.ensureCapacity(50);

        // Print capacity after ensuring
        System.out.println("Capacity after ensuring: " + sb.capacity());
    }
}

Output:

Initial capacity: 100
Capacity after ensuring: 100

Real-World Use Case

Example: Optimizing Capacity for Logging

In a real-world scenario, you might use StringBuilder to construct log messages dynamically. By ensuring sufficient capacity at the start, you can avoid multiple memory reallocations during the logging process, optimizing performance.

Example Code

public class Logger {
    private StringBuilder logBuilder;

    public Logger() {
        // Initialize the StringBuilder with an estimated capacity
        logBuilder = new StringBuilder();
        logBuilder.ensureCapacity(100); // Ensure at least 100 characters capacity
    }

    public void log(String message) {
        // Append a timestamp and the message to the log
        logBuilder.append(System.currentTimeMillis())
                  .append(" - ")
                  .append(message)
                  .append("\n");
    }

    public String getLogs() {
        // Convert StringBuilder to String and return the logs
        return logBuilder.toString();
    }

    public static void main(String[] args) {
        Logger logger = new Logger();

        // Log some messages
        logger.log("Starting the application");
        logger.log("Performing some operations");
        logger.log("Application finished successfully");

        // Retrieve and print the logs
        String logs = logger.getLogs();
        System.out.println("Logs:\n" + logs);
    }
}

Output:

Logs:
<timestamp> - Starting the application
<timestamp> - Performing some operations
<timestamp> - Application finished successfully

Conclusion

The StringBuilder.ensureCapacity() method in Java is used for optimizing the performance of string manipulations by pre-allocating memory. By understanding how to use this method, you can efficiently manage the internal buffer of a StringBuilder object and avoid frequent memory reallocations. Whether you need to ensure a minimum capacity for future operations or check the capacity before and after ensuring, the ensureCapacity method provides a reliable solution for these tasks.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top