Java.lang.StringBuilder.capacity() Method

Advertisements


Description

The java.lang.StringBuilder.capacity() method returns the current capacity. The capacity is the amount of storage available for newly inserted characters, beyond which an allocation will occur.

Declaration

Following is the declaration for java.lang.StringBuilder.capacity() method

public int capacity()

Parameters

  • NA

Return Value

This method returns a reference to this object.

Exception

  • NA

Example

The following example shows the usage of java.lang.StringBuilder.capacity() method.

package com.tutorialspoint;

import java.lang.*;

public class StringBuilderDemo {

  public static void main(String[] args) {
  
    StringBuilder str = new StringBuilder("CompileOnline");

    /* returns the current capacity of the StringBuilder i.e.
     16 + 13 */
    System.out.println("capacity = " + str.capacity());
    
    str = new StringBuilder(" ");
    // returns the current capacity of the StringBuilder i.e. 16 + 1
    System.out.println("capacity = " + str.capacity());
  }
}  

Let us compile and run the above program, this will produce the following result:

capacity = 29
capacity = 17



Advertisements
Advertisements