Jul 16, 2008

Difference between String and StringBuffer

The String class is final and String objects are immutable which means that the value of String objects can’t be modified.
But there are situations where one needs to modify the underlying String text. To solve this problem, java has StringBuffer class whose objects are mutable and can be modified using the methods. This means that instead of returning a new object as in case of String class, the methods of StringBuffer class return the modified object.

Other thing to note about StringBuffer class is that the methods are synchronized. StringBuilder is another class whose objects are mutable but its methods are not synchronized.

For the SCJP exam, it is crucial to know that StrigBuffer class has constructor which can accept an object of type String but the reverse is not true.
Moreover, the String and StringBuffer objects are never equal to each other even if the underlying text is same for both.

No comments:

Post a Comment