Java-Difference Between Length and Capacity

Difference Between Length and Capacity

The major difference between the length and the capacity of the StringBuffer object is, the length increase by the number of character append to the string. The capacity is increased only when the current capacity is exceeded by the new length.

Program

NJNJ

Program Source

public class Javaapp {
    
    public static void main(String[] args) {
        
        StringBuffer str = new StringBuffer(3);
        System.out.println("str length   : "+str.length());
        System.out.println("str capacity : "+str.capacity());
        
        str.append("AB");
        System.out.println("str content  : "+str);
        System.out.println("str length   : "+str.length());
        System.out.println("str capacity : "+str.capacity());
        
        str.append("CDEF");
        System.out.println("str content  : "+str);
        System.out.println("str length   : "+str.length());
        System.out.println("str capacity : "+str.capacity());
        
        str.append("GHI");
        System.out.println("str content  : "+str);
        System.out.println("str length   : "+str.length());
        System.out.println("str capacity : "+str.capacity());
    }
}

Leave a Comment