Thursday, July 12, 2012

Difference between string and stringbuffer in java with example?

Difference between string and stringbuffer in java with example:

   The main difference between String and StringBuffer is, String objects are immutable and StringBuffer objects are mutable. Here Immutable means we can not change the contents of an object. Consider the following example.

Example for String Immutable:

String name1="Hello";   //Hello will be stored in name1

String name2="World";    //World will be stored in name2

name1=name1+name2; //Trying to add something to Hello

System.out.println(name1);

Output:

HelloWorld

             In the above example we said that String objects are immutable, but the content of name1 is changed from Hello to HelloWorld. It is little surprising right?,Here the reason is when we are trying to add two strings a new object is created. Here the new object is HelloWorld. In place of Hello the HelloWorld will be replaced. This will be done internally. We can not notice that.

Example for StringBuffer mutable:

StringBuffer name1=new StringBuffer("Hello"); //Hello will be stored in name1
StringBuffer name2=name1; // We are assigning Hello to name2 also
 name2.append("World"); // We are adding an World to Hello
System.out.println(name1);
System.out.println(name2);


Output:

HelloWorld
HelloWorld

                   In the above example we  are trying to change the contents of name2. Here we are adding World to name2.  When displaying name1, it should print Hello and when displaying name2 it should print HelloWorld. But Cleary Observe, In the above example both name1 and name2 are printing HelloWorld only. Here the reason is, both name1 and name2 are sharing the same object. When we change the content of an object, the same object will be changed. Here new object will not be created.