The equals() method present in Object class is used for comparing two objects are pointed out the same memory or not. See the below example.
public class EqualsDemo {
public static void main(String[] args) {
EqualsDemo obj1 = new EqualsDemo();
EqualsDemo obj2 = new EqualsDemo();
// The obj3 just refer the obj1 memory
EqualsDemo obj3 = obj1;
if(obj1.equals(obj2)) {
System.out.println("The object1 and object2 are equals");
}
else{
System.out.println("The object1 and object2 are not equals");
}
if(obj1.equals(obj3)) {
System.out.println("The object1 and object3 are equals");
}
else{
System.out.println("The object1 and object3 are not equals");
}
}
}
In this example I have created the two objects (obj1, obj2) for class EqualsDemo. The obj3 is just pointed out the obj1 memory. Finally I compared the object1 and object2 as well as object1 and object3. The result should be like this.
The object1 and object2 are not equals
The object1 and object3 are equals
public class EqualsDemo {
public static void main(String[] args) {
EqualsDemo obj1 = new EqualsDemo();
EqualsDemo obj2 = new EqualsDemo();
// The obj3 just refer the obj1 memory
EqualsDemo obj3 = obj1;
if(obj1.equals(obj2)) {
System.out.println("The object1 and object2 are equals");
}
else{
System.out.println("The object1 and object2 are not equals");
}
if(obj1.equals(obj3)) {
System.out.println("The object1 and object3 are equals");
}
else{
System.out.println("The object1 and object3 are not equals");
}
}
}
In this example I have created the two objects (obj1, obj2) for class EqualsDemo. The obj3 is just pointed out the obj1 memory. Finally I compared the object1 and object2 as well as object1 and object3. The result should be like this.
The object1 and object2 are not equals
The object1 and object3 are equals
Comments