Skip to content
Related Articles

Related Articles

Difference Between Length and Capacity in Java

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 19 Jan, 2022

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. 

Syntax:

public int length () 

Example:

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
    }
}


Output

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. 

Syntax:

public int capacity

Example: The file name is 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)
    }
}


Output

capacity:25

Difference Between Length and Capacity

S. No Length 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. 

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!