my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in equals() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt in equals()" Watch "Doubt in equals()" New topic

Doubt in equals()

Guru dhaasan
Ranch Hand

Joined: Sep 13, 2006
Posts: 126

In the following code:
public class eq{
public static void main(String args[]){
obj1 oba=new obj1(1,2);
obj1 obb=new obj1(1,2) ;
if (oba.equals(obb)){System.out.println("oba == obb");}
else {System.out.println("oba!=obb");}
obj2 ob2=new obj2();
if (ob2.equals(oba)) {System.out.println("ob2==oba");}
else {System.out.println("ob2!=oba");}

class obj1{
private int x=0;
private int y=0;
obj1(int x,int y){
public int getX(){
return this.x;
public int getY(){
return this.y;

class obj2{
private int x=1;
private int y=2;
public boolean equals(Object ob){
obj1 one=(obj1)ob;
if ((one.getX()==x)&&(one.getY()==y)){
return true;
return false;

The output is:

Why the first output is not equal???
After all, equals method compares bit by bit and both oba and obb has exactly the same contents

Any explanation appreciated.


Thanks, Shiv
SCJP, OCE - JSP & Servlets Developer
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1710

Because for class obj1 you have not overridden the eqauls() method.

Thanks and Regards,

lalitha kalanadhbhatla

Joined: Nov 05, 2006
Posts: 7
Hai Guru,
As you sent the values 1,2 to the constructor of obj1 the values are passed by value.The changes takes place in the class obj1 but the values are not returned to main class as the pass by value only makes a change to copy that is passed to the obj1 but the main class remains unaffected.
Prasanna Venkatesh

Joined: Dec 01, 2004
Posts: 11
Hi Guru ,
If your not overriding the equals method , it will just bit compare the object referecenes. So in the first case obviuosly it wont be equal , since they are reffering different object .
If you add some thing like this
obj1 obc= obb;
then always
if ( obb.equals(obc) )

will return true .since they are reffering same objects. Hope this helps
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1710
Try this modified code,

Thanks and Regards,
Arad Chear
Ranch Hand

Joined: Jan 05, 2007
Posts: 98
while you not override equal method in obj1 the original method ( in class Object ) will test only throw == operator

so you test two different reference so oba!=obb but its meaningfully equal that doesn't matter if you don't override the equal method

its like this :

if (oba==obb){System.out.println("oba == obb");}
else {System.out.println("oba!=obb");}
I agree. Here's the link:
subject: Doubt in equals()
jQuery in Action, 3rd edition