StringBuffer sb1 = new StringBuffer("Java");
StringBuffer sb2 = new StringBuffer("Java");
System.out.println(sb1 == sb2);
System.out.println(sb1.equals(sb2));
Here both are returning false. How is it possible?
StringBuffer sb1 = new StringBuffer("Java");
StringBuffer sb2 = new StringBuffer("Java");
System.out.println(sb1 == sb2);
System.out.println(sb1.equals(sb2));
Here both are returning false. How is it possible?
The equals method of StringBuffer is not overridden from Object, so it is just reference equality, i.e., the same as using ==. I suspect the reason for this is that StringBuffer is modifiable, and overriding equals is mostly useful for value-like classes that you might want to use as keys (though lists also have an overridden equals and StringBuffer is kind of a list, so this is a bit inconsistent).
You are comparing the references to the StringBuffer objects rather than the actual strings within the StringBuffer.
System.out.println(sb1.toString().equals(sb2.toString())) would return true and I assume this is what you had expected or wanted to achieve.
StringBuffer seems to have no equals method of its own, so my first guess would be that StringBuffer inherits the equals method of Object, which compares using sb1 == sb2. Therefore, both methods yield the same result.
both compares two references to objects (sb1 is one, and sb2 is second), thus both are different.
If You are trying to compare content - use method compareTo(...) in String class - that is - first get String content of StringBuffer using method toString() (.toString().compareTo).
Ps. as of JDK 5, there is another much faster class that behaves exactly as StringBuffer - it is StringBuilder, and is also but is not thread safe.
StringBuffer sb1 = new StringBuffer("Java");
StringBuffer sb2 = new StringBuffer("Java");
System.out.println(sb1.toString().compareTo(sb2.toString()));
The simple answer is that StringBuffer (and StringBuilder) do not redefine the base semantics of Object.equals(). So equals on a StringBuffer will simply compare object references.
In fact, String, StringBuffer, StringBuilder and CharBuffer all implement the CharSequence interface, and the javadoc for this interface says this:
This interface does not refine the general contracts of the equals and hashCode methods. The result of comparing two objects that implement CharSequence is therefore, in general, undefined. Each object may be implemented by a different class, and there is no guarantee that each class will be capable of testing its instances for equality with those of the other. It is therefore inappropriate to use arbitrary CharSequence instances as elements in a set or as keys in a map.
Wondering why StringBuffer does not override the equals method. Probably because the content of the object is obtained by the toString() method and which has the desired method.