📜  Java中长度和容量的区别

📅  最后修改于: 2022-05-13 01:55:34.846000             🧑  作者: Mango

Java中长度和容量的区别

长度和容量在Java中是两个不同的东西。当字符附加到字符串时,长度基本上会增加,而当当前容量超过新长度时,容量会增加。

length() 方法是Java String 类的一部分。它用于查找字符串的长度。它基本上计算字符串字符。因此该方法返回一个整数。整数只不过是字符数。它还将空格计为字符。它是一个最终变量,仅应用于字符串对象。

句法:

public int length () 

例子:

Java
// Java Program to demonstrate 
// the length function
  
public class length_string {
  
    public static void main(String args[])
    {
  
        String s = "GeeksforGeeks Java";
  
        System.out.println("String length " + s.length());
  
        // Output is String length 18
    }
}


Java
// Java Program to demonstrate 
// the capacity function
  
public class capacity_example {
  
    public static void main(String args[])
    {
  
        StringBuffer s = new StringBuffer("Gfgstring");
  
        System.out.println("capacity:" + s.capacity());
  
        // The output is capacity:25 (because 16+9 where
        // length of Gfgstring is 9)
    }
}


输出
String length 18

capacity() 方法是 StringBuffer 类的一部分。它基本上表示可用于存储新字符的空间量。该方法返回字符串缓冲区的当前容量。默认情况下,一个空的 StringBuffer 包含 16 个字符的容量。因此,当添加新字符时,输出是返回字符长度 +16。

句法:

public int capacity

示例:文件名为 capacity_example。Java

Java

// Java Program to demonstrate 
// the capacity function
  
public class capacity_example {
  
    public static void main(String args[])
    {
  
        StringBuffer s = new StringBuffer("Gfgstring");
  
        System.out.println("capacity:" + s.capacity());
  
        // The output is capacity:25 (because 16+9 where
        // length of Gfgstring is 9)
    }
}
输出
capacity:25

长度和容量之间的差异

S. NoLengthCapacity
1.It is a part of the String class. It is part of the StringBuffer class. 
2.It is used to find the length of the string. It is used to find the capacity of StringBuffer. 
3.By default, the length of an empty string is 0.By default, an empty string buffer contains 16 character capacity. 
4.It is the actual size of the string that is currently stored. It is the maximum size that it can currently fit. 
5.One can count the length by simply counting the number of characters. The capacity can be calculated by counting the number of characters and adding 16 to it.