Home » Java programming language

Java StringBuilder capacity() method with example

StringBuilder Class capacity() method: Here, we are going to learn about the capacity() method of StringBuilder Class with its syntax and example.
Submitted by Preeti Jain, on December 21, 2019

StringBuilder Class capacity() method

  • capacity() method is available in java.lang package.
  • capacity() method is used to return the current capacity (i.e. it returns the initial capacity + new occupied characters) and capacity indicates the amount of storage vacant for allowing newly occupying will occur.
  • capacity() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • capacity() method does not throw an exception at the time of returning capacity.

Syntax:

    public int capacity();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of this method is int, it returns a reference to this StringBuilder object.

Example:

// Java program to demonstrate the example 
// of int capacity() method of StringBuilder 

public class Capacity {
    public static void main(String[] args) {
        // Creating an StringBuilder object
        StringBuilder st_b = new StringBuilder("Java");
        System.out.println("st_b = " + st_b);

        // By using capacity() method to display current capacity 
        // of st_b object i.e. 16(initial) + 4(No.of char consumed) //i.e.20
        System.out.println("st_b.capacity() = " + st_b.capacity());

        // Creating another StringBuilder object
        st_b = new StringBuilder("Programming");
        System.out.println("st_b = " + st_b);

        // By using capacity() method to display current capacity 
        // of st_b object i.e. 16(initial) + 11(No.of char consumed) //i.e.27
        System.out.println("st_b.capacity() = " + st_b.capacity());
    }
}

Output

st_b = Java
st_b.capacity() = 20
st_b = Programming
st_b.capacity() = 27



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.