String Buffer Class in Java

 StringBuffer class is the peer class of String. It enables us to create flexible length string allow us to perform manipulation on a string whenever we want. 

Commonly used StringBuffer Methods: 

1. str1.setCharAt (n, char ch) It modifies the nth character to ch. 

 StringBuffer str=new StringBuffer("Cello"); 
 str .setCharAt (0 , 'H'); //output string Hello  

2. str1.append (str2) – Appends the string str2 at the end of string str1.

 StringBuffer str=new StringBuffer("Hello"); 
 str . append (" GoodMorning "); //output string Hello GoodMorning  

3) str1.insert (n,s2) – It inserts the string str2 at the position n of the string str1.

 StringBuffer str=new StringBuffer("Hello Good Morning"); 
 str.insert (5, " class ");  

4) str1.setLength( n) – sets the length of the string str1 to n.  

 str.setLength(30); 
 If n < str1. length( ) then str1 is truncated. 
 If n > str1 .length ( ) then zeros are added to str1. 

Here I have listed most commonly used methods of StringBuffer class

No. Method call  Action performed
s1.setCharAt( );  Modifies the nth character to x
s1.append( s2 ); Appends string to s2 to s1at the end
s1.insert( n, s2 ); Insert the string s2 at the position n of the string s1
s1.setLength( n ) Sets the length of the string s1 to n. If n < s1.length( ) then s1 is truncated. If n > s1.length( ) then zeros are added to s1

Rutu Shah