Friday 24 August 2012

Compare two StringBuffer objects in Java

We can't use the equals method of the StringBuffer class for comparing two StringBuffer objects.The StringBuffer class equals method returns true only if both the comparing objects pointing to the same memory location.i.e. here comparing the memory address of the StringBuffer objects, not their contents.

Hence we have to convert the StringBuffer objects to String and use the String class equals method for comparing StringBuffer objects.String class equals method returns true if both the String objects occupies the same content.

See the example given below:


public class CompareStringBuffer {

	public static void main(String[] args) {

		StringBuffer sb1 = new StringBuffer("Java");
		StringBuffer sb2 = new StringBuffer("Java");

		System.out.println("sb1.equals(sb2)=" + sb1.equals(sb2));
		System.out.println("Is sb1 equals sb2?="
				+ sb1.toString().equals(sb2.toString()));

	}
}


The output is:


sb1.equals(sb2)=false
Is sb1 equals sb2?=true

No comments:

Post a Comment