Java StringBuilder capacity()方法及示例

Java StringBuilder capacity()方法及示例

StringBuilder类capacity() 方法用于返回StringBUilder对象的当前容量。该容量是可用于 插入新字符 的存储量 。

语法:

public int capacity()

返回值: 该方法返回StringBuilder类的 当前容量

以下程序演示了StringBuilder类的capacity()方法:

示例1:

// Java program to demonstrate
// the capacity() Method.
 
class GFG {
    public static void main(String[] args)
    {
 
        // create a StringBuilder object,
        // default capacity will be 16
        StringBuilder str = new StringBuilder();
 
        // get default capacity
        int capacity = str.capacity();
 
        System.out.println("Default Capacity of StringBuilder = "
                           + capacity);
 
        // add the String to StringBuilder Object
        str.append("Geek");
 
        // get capacity
        capacity = str.capacity();
 
        // print the result
        System.out.println("StringBuilder = " + str);
        System.out.println("Current Capacity of StringBuilder = "
                           + capacity);
    }
}

输出

Default Capacity of StringBuilder = 16
StringBuilder = Geek
Current Capacity of StringBuilder = 16

例2:

// Java program to demonstrate
// the capacity() Method.
 
class GFG {
    public static void main(String[] args)
    {
        // create a StringBuilder object
        // with a String passed as parameter
        StringBuilder
            str
            = new StringBuilder("WelcomeGeeks");
 
        // get capacity
        int capacity = str.capacity();
 
        // print the result
        System.out.println("StringBuilder = " + str);
        System.out.println("Capacity of StringBuilder = "
                           + capacity);
    }
}

输出

StringBuilder = WelcomeGeeks
Capacity of StringBuilder = 28

参考资料:
https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#capacity()

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程