StringBuffer class

StringBuffer class used to make string object which are mutable. It means string stored in stringbuffer variable can be changed. String class don't allow changes in string. String class is immutable means it can't be changed, all can be done is creation of new object with changed data.

Example :


class sb 
{
static void main(String arg[])
{
StringBuffer st=new StringBuffer("hello");
System.out.println("st:"+st);
//after changing string

st.append(" java");
}
}



Example :


class sb 
{
static void main(String arg[])
{
StringBuffer st=new StringBuffer("hello");
System.out.println("st:"+st);
//after changing string
StringBuilder st1=st.append("java");
if(st1==st)
System.out.println("same object");
else
System.out.println("different objects");
}
}
/* Output:
same object
*/

Note ! StringBuffer is mutable, means it can be changed. StringBuffer takes memory from heap. StringBuffer is thread safe, which means at a time only one method can call method of StringBuffer class. All methods are synchronized.

Because of thread safe property StringBuffer execute slower that StringBuilder.