当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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("Deafult 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); 
    } 
}
输出:
Deafult 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()



相关用法


注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 StringBuilder capacity() in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。