You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
publicclassMainApp {
publicstaticvoidmain(String[] args) {
Students1 = newStudent("Anu");
Students2 = newStudent("Ann");
Students3 = newStudent("Ann");
// Comparing two objects using .equals()System.out.println(s1.equals(s2)); // false - content not sameSystem.out.println(s2.equals(s3)); // true - content same // value of instance variable same
}
}
equals()
equals() is a method used to compare two objects in java.
2 objects are said to be equal -
> When they belong to the same class type.
> values of instance variables should be same
> 2 objects are going to have same hashcode
NOTE: When 2 objects are equal >> they will have same hashcode value!
Internal representation of .equal()
@Overridepublicbooleanequals(Objectobj) { // comparing 2 objects// parameter is of parent class// datatype of reference is obj// Step 1: Check if both references point to the same objectif (this == obj) { // this talks about the current instance// comparing s1.equals(s1)returntrue; // then return true!
}
// Step 2: Check if the passed object is null if (obj == null )// passing null - couldn't compare which doesn't exist ie obj reference is NULLreturnfalse; // return false!// step 3: ocheck if the passed obj is of the same classif(getClass() != obj.getClass()) { // getClass() gives the class type // if 2 classes are not equal - return falsereturnfalse; // return false
}
// Then do type casting - after that value of each instance variable of one object is compared with other one.
Where do we use .equals() in Automation Framework?
.equals() is commonly used in assertions to compare expected and actual results