Monday, September 26, 2011

StringBuffer and StringBuilder are mutable (Example)


//Bellow program shows that StringBuffer/StringBuilder is mutable
package StringBuffered;
public class StringObjectIsImmutable
{
public static void main(String[] arun)
{
//StringBuffered is mutable and synchronized.
StringBuffer name = new StringBuffer("Arun");
System.out.println(name);
name.append(" Kumar");
// in the above line like String object no new StringBuffered Object (name) is created. That's the reason executable time for StringBuffer/String Builder is faster than String.
System.out.println(name);
/*//StringBuffered is mutable and not synchronized
StringBuilder name = new StringBuilder("Arun");
System.out.println(name);
name.append(" Kumar");
// in the above line like String object no new StringBuffered Object (name) is created. That's the reason executable time for StringBuffer/String Builder is faster than String.
System.out.println(name);*/
}
}
Output =>
Arun
Arun Kumar

No comments:

Post a Comment