0
StringBuffer str1=new StringBuffer("hello1");
StringBuffer str2=new StringBuffer("hello1");
System.out.println(str1.equals(str2));

It will Showing False result Why?

leppie
  • 115,091
  • 17
  • 196
  • 297
Pankaj Bansal
  • 367
  • 4
  • 17
  • possible duplicate of [Comparing StringBuffer content with equals](http://stackoverflow.com/questions/2012305/comparing-stringbuffer-content-with-equals) – Maroun Jan 29 '15 at 09:57
  • See [`Object#equals`](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Object.java#Object.equals%28java.lang.Object%29) code. – Maroun Jan 29 '15 at 09:59

2 Answers2

2

StringBuffer equals() method isn't overridden to check content. It's using the default "shallow equals" that compares references it inherits from java.lang.Object.

So

StringBuffer str1=new StringBuffer("hello1");
StringBuffer str2=new StringBuffer("hello1");
System.out.println(str1.equals(str2));

is Comparing reference that is why you are getting false

Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62
1

There is no overriding of equals in the StringBuffer class. So it inherits the definition from Object class. And from Java API we know its behavior:

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

You have two different objects, so equals return false in this case.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69