wood burning stoves 2.0*
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
Author

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
--------------------------------------------------------

Here:
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,
seetharaman.v
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
Sheriff

Joined: Oct 13, 2005
Posts: 37958
    
  22
Lots more details available in this recent thread.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: types in equals()???
 
Similar Threads
equals() in Wrapper Classes
cannot find symbol
Regarding StringBuffers
a simple quiz on string equals
in what condition the equls to compare whether the two are the same object?