Meaningless Drivel is fun!
The moose likes Beginning Java and the fly likes .equals method for objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply locked New topic

.equals method for objects

Nitin Singla

Joined: Oct 05, 2011
Posts: 15

class testToString
public static void main(String args[])
Integer i=new Integer(4);
Integer y=new Integer(4);
checkToString cs = new checkToString(2);
checkToString c = new checkToString(2);
if( cs.equals(c))
System.out.println(" Both objects are equal");
System.out.println(" Unequal objects ");
if( i.equals(y))
System.out.println(" i,y - Both objects are equal");
System.out.println(" i,y - Unequal objects ");
class checkToString
int i;
checkToString(int a)

In my above class, i & y are giving true on using i.equals(y) and cs & c objects are giving false on using cs.equals(c). In both the cases we are not overriding equals() method. Can someone helps me here?
Jeff Verdegan

Joined: Jan 03, 2004
Posts: 6109

As I stated in the other thread where you asked this question, what we do in our class doesn't matter here. It's Sring's and Integers equals() methods that are being called (as we can see clearly from the code), so it's what String and Integer do with equals() that matters. And both of those classes override equals(), as you can see in their javadocs.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46349
Jeff Verdegan wrote:As I stated in the other thread where you asked this question, . . ..
For reasons stated here, it would cause confusion if you ask the same question twice.

And welcome to the Ranch
I agree. Here's the link:
subject: .equals method for objects
It's not a secret anymore!