.capacity()

Christine_Yang269 total contributions
Published Aug 22, 2022Updated Aug 22, 2022
Contribute to Docs
The .capacity()
method returns the current space available for characters in the StringBuilder
, whereas .length()
returns the number of characters actually in use.
Syntax
myStringBuilder.capacity()
The .capacity()
method takes no arguments.
Example
The following example creates a StringBuilder
with a specified String
, then displays the capacity of the StringBuilder
before and after using the .delete()
method to change its contents:
import java.util.*;public class Example {public static void main(String[] args){StringBuilder str = new StringBuilder("Hello World!");System.out.println(str.toString());System.out.println(str.capacity());str.delete(0,6);System.out.println(str.toString());System.out.println(str.capacity());}}
This produces the following output:
Hello World!28World!28
All contributors
- Christine_Yang269 total contributions
- StevenSwiniarski466 total contributions
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.