Java-StringBuffer

StringBuffer

The StringBuffer class is the companion class of the String class. The objects of the String class represent fixed-length, immutable character sequences. On the other hand, the objects of the StringBuffer class represent growable and mutable character sequences. The methods that are available in the StringBuffer class make it possible to insert a substring in the middle or append a substring at the end of an object of the StringBuffer class. The size of the StringBuffer object will be automatically increased so as to make room for such insertions and additions. The append( ) method enables you to add a string to the end of the existing string stored in a StringBuffer object.

Constructors for StringBuffer

In the first case, the StringBuffer has no parameters. So it will reserve area for ’16’ characters. The second one is accept an integer value it set the size. The third one is set the initial value and reserve area for ’16’ more characters. It is providing the flexibility for changing a string require substantial space and complexity. Every StringBuffer has two methods they are length( ) and capacity( ).

The length( ) method returns the current length of a StringBuffer object. The capacity( ) method returns the allocated capacity of a StringBuffer object.

Progarm

trtrt

Program Source

public class Javaapp {
    
    public static void main(String[] args) {
        
        StringBuffer str1 = new StringBuffer();
        StringBuffer str2 = new StringBuffer(20);
        StringBuffer str3 = new StringBuffer("Java");
        
        str1.append("C Programming");
        str2.append("C++ Programming");
        str3.append(" Programming");
        
        System.out.println("str1 content  : "+str1);
        System.out.println("str2 content  : "+str2);
        System.out.println("str3 content  : "+str3);
        
        System.out.println("str1 length   : "+str1.length());
        System.out.println("str2 length   : "+str2.length());
        System.out.println("str3 length   : "+str3.length());
        
        System.out.println("str1 capacity : "+str1.capacity());
        System.out.println("str2 capacity : "+str2.capacity());
        System.out.println("str3 capacity : "+str3.capacity());

    }
}

Leave a Comment