File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes equals() method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "equals() method" Watch "equals() method" New topic

equals() method

Arun Maalik
Ranch Hand

Joined: Oct 25, 2005
Posts: 216
public class first{
public static void main(String[] args){
first p=new first();
first q=new first();
System.out.println("Not Equals");

Helo sir in the above code it is printing "Not Equals " why? also i would like to know that in which case equals function print "Equals" and in which case "Not Equals "

with Regard

Arun kumar maalik
Rusty Shackleford
Ranch Hand

Joined: Jan 03, 2006
Posts: 490
Check the API description of equals. They may be objects of the same type but they are two different objects in memory, so it is not symmetric. It fails in the definition of equivilence relation so is not equal.

Try this:

If you want different behavior you will need to override equals().
[ July 18, 2006: Message edited by: Rusty Shackleford ]

"Computer science is no more about computers than astronomy is about telescopes" - Edsger Dijkstra
Arun Maalik
Ranch Hand

Joined: Oct 25, 2005
Posts: 216
Thanks sir Thanks a lot for java Ranch
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46405
override equals().
. . . and don't forget to override hashCode() too.
ak pillai
Ranch Hand

Joined: Feb 11, 2006
Posts: 288
== is a shallow comparison, which only compares the identity.

The == returns true, if the variable reference points to the same object in memory. This is a �shallow comparison�.

equals() method is a deep comparison whick makes use of equals() method to make sure they are logically equal.

The equals() - returns the results of running the equals() method of a user supplied class, which compares the attribute values. The equals() method provides �deep comparison� by checking if two objects are logically equal as opposed to the shallow comparison provided by the operator ==.

If equals() method does not exist in a user supplied class then the inherited Object class's equals() method is run which evaluates if the references point to the same object in memory. The object.equals() works just like the "==" operator (i.e shallow comparison).

Overriding the Object class may seem simple but there are many ways to get it wrong, and consequence can be unpredictable behaviour.
[ July 18, 2006: Message edited by: ak pillai ]

java j2ee job interview questions with answers | Learn the core concepts and the key areas
I agree. Here's the link:
subject: equals() method
It's not a secret anymore!