Difference Between Length and Capacity in Java
Length and capacity are two different things in Java. Length basically increases when characters are appended to the string whereas the capacity increases when the current capacity is exceeded by a new length.
length () method is a part of the Java String class. It is used to find the length of the string. It basically counts the number of characters present in the string. Therefore the method returns an integer. The integer is nothing but the character count. It also counts the space as characters. It is a final variable that is applied only on string objects.
public int length ()
String length 18
The capacity () method is a part of the StringBuffer class. It basically denotes the amount of space available to store new characters. The method returns the current capacity of the string buffer. By default, an empty StringBuffer contains 16 character capacity. So when new characters are added the output is the length of characters+16 is returned.
public int capacity
Example: The file name is capacity_example.java
Difference Between Length and Capacity
|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.|
|6.||Length is considered while copying elements from one array to another||Capacity is not considered while copying elements.|
|7.||Length can be modified only by removing elements from the array||Capacity can be increased by reallocating the memory.|
Please Login to comment...