-2
class A 
{ 
   int a=10,b=10,c=10; 
} 
class Equals 
{ 
     public static void main(String s[]) 
   { 
     A a,b; 
     a=new A(); 
     b=new A(); 
     if(a.equals(b))
      {

         System.out.println("We r same..."); 
      }
     else
         {

          System.out.println("We r not same...");

         } 
    } 
}

Why is this code not printing output as we r same?
I am not able to understand the logic behind this program.

chenzhongpu
  • 6,193
  • 8
  • 41
  • 79
Aryan Ragavan
  • 117
  • 1
  • 6
  • 2
    Possible duplicate of [How equals() method works](http://stackoverflow.com/questions/16089282/how-equals-method-works) – ControlAltDel Oct 18 '15 at 08:54

6 Answers6

2

Those to objects are not same because you are checking reference equality. you have to use equals() method.

Add this to your class A :

@Override
    public boolean equals(Object obj) {
        // TODO Auto-generated method stub
        A ref = (A)obj;
        return ref.a == this.a && ref.b == this.b && ref.c == this.c ;
    }

And instead of writing a==b check a.equals(b)

Rahman
  • 3,755
  • 3
  • 26
  • 43
1

By default the equals method will return whether the two objects are actually the same. In your case they are different, hence the output.

You can look at this this way - you haven't told what do you consider as "equality" of your object A.

The way to solve it would be to implement equals method for your A class.

Roman Pustylnikov
  • 1,937
  • 1
  • 10
  • 18
1

This is because '==' operator checks only that both objects are referencing the same memory or not. If both are referencing same location, it returns true.

For ex : a=new A(); b=a;

Then, a==b returns true, because both are pointing same location.

Ambika
  • 594
  • 2
  • 11
0

Equals() in java compares objects to see if they're the same object somewhat. The two objects you created have different references so equals will not return a true. Misread this the first time.

Feek
  • 297
  • 3
  • 15
0

The equals is an method inherited from object, you can override it as you need.

class A 
{ 
   public int a=10,b=10,c=10;
   public boolean equals(Object a){
     if(a == null) return false;
     if(!(s instance A)) return false;
     A other = (A)a;
     if(other.a == this.a && other.b = this.b && other.c == other.c)
       return true;
     return false;
   }
}

see Overriding the java equals() method quirk.

Community
  • 1
  • 1
chenzhongpu
  • 6,193
  • 8
  • 41
  • 79
0

a and b are different instances of class A. why do you think they should equal to each other because they have the same class?

you should override equals method in class A to implement your own logic for determine if two instances of class A equal to each other or not. for example:

public boolean equals(Object o) {
      if (o==null) return false;
     A o2 = (A) o;
     return this.a == o2.a && this.b == o2.b && this.c == o2.c;
}
Bon
  • 3,073
  • 5
  • 21
  • 40