my dog learned polymorphism
The moose likes Beginning Java and the fly likes types in equals()??? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "types in equals()???" Watch "types in equals()???" New topic

types in equals()???

Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Hi All,

definition of equals(): checks whether two objects are meaningfully equivalent or not

see here
public class Merrill{

public static void main(String[] args){

StringBuffer sb=new StringBuffer("seetha");
StringBuffer se=new StringBuffer("seetha");
System.out.println(sb.equals(se));//return false?

}//end of main method

}//end of class Merrill

System.out.println(sb.equals(se));//return false?

it should be true right? then y it is giving false..

but if you replace StringBuffer with String then answare is true..

can anyone explain me ?

Thanks & Regards,
amitabh mehra
Ranch Hand

Joined: Dec 05, 2006
Posts: 98
StringBuffer inherit equals() from Object class, they do not override this method. While String class overrides equals() and returns the result -
"result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object."
(-- javadoc), StringBuffer implementation of equals will be something like:

So this returns true only when compared to itself. In one way, that is expected as you can always do s1.toString().equals(s2.toString())

Hence, StringBuffer use identity to determine equality, not contents. Whereas, strings use contents to determine equality.

Hope I cleared your doubt.
Vikas Kapoor
Ranch Hand

Joined: Aug 16, 2007
Posts: 1374
Hello Seetharaman,

The catch is String class overrides the equals() method. So it checks the actual contents.

While StringBuffer class inherits the equals() method from Object class. So it actually checks whether two stringbuffer references refer to same object or not.

And yes,

-- Use CODE tag to enclose your code.
-- Use Real words (Why? Y)

you are not newbie now.
[ June 02, 2008: Message edited by: Vishal Pandya ]
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Thanks Amitabh and Vishal Pandya
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46367
Lots more details available in this recent thread.
I agree. Here's the link:
subject: types in equals()???
It's not a secret anymore!