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

equality doubt

Ravindra Harige
Ranch Hand

Joined: Jun 10, 2005
Posts: 33

why the output of above code is

and not


Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
This has come up recently. Search the forums for it.

Of course, using == to compare the values of objects is almost always wrong anyway.

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Ricky Martaputra
Ranch Hand

Joined: Apr 04, 2005
Posts: 42
that's the autoboxing feature..

Compare two Integers with '==' only return true with between -128 to 127.
Otherwise, it returns false.
prateek chaudhari

Joined: Oct 14, 2006
Posts: 11
Its all about references comparison.

If I am not wrong ..You have crated 4 Integer objects, when you compare object references using == then the values inside reference (which is something how to get object values from heap) is checked while when you use equals() method which is inherited by every class in Java you compare the values pointed by the reference variables.

So its not necessary that always your first condition evaluates to true.

but your second condition will always evaluate to true,(Till values are same.) cause equals() is overridden in Integer class.
[ August 09, 2007: Message edited by: prateek chaudhari ]

Prateek<br />SCJP 1.5
Ravindra Harige
Ranch Hand

Joined: Jun 10, 2005
Posts: 33
thanks a lot !
wood burning stoves
subject: equality doubt
jQuery in Action, 3rd edition