Monday, 24 March 2014

equals() : Objects Equality

boolean equals(Object obj)
Returns true if two objects are equal. The implementation like below.

   public boolean equals(Object obj) {
        return (this == obj);
    }


class Equals{
 public static void main(String args[]){
  Equals obj1 = new Equals();
  Equals obj2 = new Equals();
  Equals obj3 = obj1;
  
  System.out.println("Is obj1 and obj2 are equals " + obj1.equals(obj2));
  System.out.println("Is obj1 and obj3 are equals " + obj1.equals(obj3));
 }
}

Output
Is obj1 and obj2 are equals false
Is obj1 and obj3 are equals true

If the parameter for the equals is null, then equals method return false.

class ObjectEquals{
 public static void main(String args[]){
  Equals obj1 = new Equals();
  Equals obj2 = null;
  
  System.out.println("Is obj1 and obj2 are equals " + obj1.equals(obj2));
 }
}


Output

Is obj1 and obj2 are equals false

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment