Thursday, 25 July 2013

What is the differnce between String and StringBuffer class?

The basic differnece between String and StringBuffer class is String is immutable(means value stored in string object cannot be changed) where as StringBuffer is not.

Whenever you do any changes to your String object,it creates a new string object and does not change the existing object.

For ex:

So suppose you declare a String object:

 String test= “Hello”;  

Next, you want to append “Guest” to the same String. What do you do?


 test=test+"Guest";  


When you print the contents of test the output will be “Hello Guest”. Although we made use of the same object(test), internally a new object was created in the process. So, if you were to do some string operation involving an append or trim or some other method call to modify your string object, you would really be creating those many new objects of class String.This creates a performance issue.

In order to avoid this performance issue ,we use StringBuffer/StringBuilder class to efficiently use append and other string operations.

No comments:

Post a Comment