Menu
Topics Index
...
`

StringBufferDemo1 - Java Example Program


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.

© meritcampus 2019

All Rights Reserved.

Open In App