Menu
Topics Index
...
`


Strings > StringBuffer >
Siva Nookala - 05 Apr 2016
The length is the character count of the sequence of characters currently represented by StringBuffer.
The capacity is the amount of storage available for newly inserted characters, beyond which an allocation will occur.

StringBuffer Methods:
MethodDescription
int capacity()Returns the current capacity.
int length()Returns the length (character count).

StringBufferDemo1
class StringBufferDemo1
{
    public static void main(String[] args) {
    
        StringBuffer buff = new StringBuffer("");
    
        // returns the current capacity of the String buffer i.e. 16 + 0
        System.out.println("empty capacity = " + buff.capacity());
    
        // printing the length of empty StringBuffer
        System.out.println("empty length = " + buff.length());
    
        buff = new StringBuffer("Java"); // LINE A
    
        // returns the current capacity of the String buffer i.e. 16 + 4
        System.out.println("Java capacity = " + buff.capacity());
    
        // printing the length of StringBuffer
        System.out.println("Java length = " + buff.length());
    
    }
}
OUTPUT

empty capacity = 16
empty length = 0
Java capacity = 20
Java length = 4

DESCRIPTION

First the capacity and length of an empty StringBuffer is printed. Next the capacity and length of StringBuffer containing "Java" is printed.

THINGS TO TRY
  • Try for the below code.
    StringBuffer sb = new StringBuffer(6);
    System.out.println("Initial capacity : " + sb.capacity());
    sb.append("Merit Campus");
    System.out.println("Lenght of sb : " + sb.length());
    System.out.println("StringBuffer capacity : " + sb.capacity());
    The output for the above code is :
    Initial capacity : 6
    Lenght of sb : 12
    StringBuffer capacity : 14
    The initial capacity is 6. But when the capacity is exceeded the capacity will be increased as (initial capacity * 2 + 2), so the capacity will become 14.
  • Try for the below code.
    StringBuffer sb = new StringBuffer(4);
    System.out.println("Intial capacity : " + sb.capacity());
    sb.append("Merit Campus");
    System.out.println("Length of sb : " + sb.length());
    System.out.println("StringBuffer capacity : " + sb.capacity());
    The output of the above code is : Intial capacity : 4
    Length of sb : 12
    StringBuffer capacity : 12 When the modified capacity doesn't match to the string length the capacity will be changed to the string length, so here the capacity will become 12.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.