Wednesday, May 16, 2012

StringBuffer equals

Class stringBufferEqual
{
public static void main(String args[])
{
StringBuffer s1 = new StringBuffer("Amit");
StringBuffer s2 = new StringBuffer("Amit");
System.out.println(s1.equals(s2));
}
}

It's false because that's how StringBuffer is defined. In fact, per my review of the API, it does not appear that StringBuffer overrides the equals method from Object as String does. If instead you want to compare Strings held by the two StringBuffers, you could do: 
System.out.println(sb1.toString().equals(sb2.toString())); 


StringBuffer VS StringBuilder

StringBuffer came first. Sun was concerned with correctness under all conditions, so they made it synchronized to make it thread-safe just in case.


StringBuilder came later. Most of the uses of StringBuffer were single-thread and unnecessarily paying the cost of the synchronization.


Since StringBuilder is a drop-in replacement for StringBuffer without the synchronization, there would not be differences between any examples.


Simply use StringBuilder unless you really are trying to share a buffer between threads.


No comments: