aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes equals method .. comparing objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "equals method .. comparing objects" Watch "equals method .. comparing objects" New topic
Author

equals method .. comparing objects

Chris Wox
Ranch Hand

Joined: May 25, 2006
Posts: 34
Program 1

public class Equals{
public static void main(String[] args) {
Object n1 = new Object();
Object n2 = new Object();

System.out.println(n1.equals(n2));


}
}

result :false

Program 2
public class Equals{
public static void main(String[] args) {
Integer n1 = new Integer(47);
Integer n2 = new Integer(47);

System.out.println(n1.equals(n2));

}
}

result : true



Could someone please help me out to understand why the results are different
in two of the above programs

and also I am having difficulty understanding difference between == and equals method when comparing objects. please help me out ...
[ July 29, 2006: Message edited by: Chris Wox ]
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
The .equals method in Object simply performs a == comparision between object references.

Since n1 and n2 are references to different objects, the == comparison returns false.

The Integer class overrides equals and perform a comparison of the values stored in the Integer objects.
sandeep dhingra
Ranch Hand

Joined: Jul 30, 2005
Posts: 41
it is very simple remember two things...
1) equals method checks the state.
2) == checks the references. it only returns true when the references have been made equal like a=b then a==b will give true.

3) equals method in object class only returns true when the two references have been made equal like a.equals(b) true only if a=b;

so in your first example you call equals on two objects which are instances of Object calss. the equals method in Object class only returns true when the references have been made equal. so false.
in second one Integer class overrides the equals method and according to that it checks the state of the object that is 42...so true.


i hope you get it....
Ramamoorthy Periasamy
Ranch Hand

Joined: Feb 06, 2006
Posts: 30
Program 2
public class Equals{
public static void main(String[] args) {
Integer n1 = new Integer(128);
Integer n2 = new Integer(128);

System.out.println(n1.equals(n2));

}
}

result : false

You need to understand when these wrapper objects are really equal!

In order to save memory two instances of the following wrapper objects will be always be == when their primitive values are the same:
Boolean
Byte
Character from \u0000 to \u007f (7f is 127 in decimal)
short and Integer from -128 to 127
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: equals method .. comparing objects