Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Object Equality
Java Basics Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Java Basics Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency.
-->
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
When we looked at object equality in an earlier section with the equals() method for String, we discovered how it was different in functionality than the default equals method for other objects. Take a look at the two different equality functions below.
ObjectEqualityExample.java
package exlcode;
public class ObjectEqualityExample {
public static void main(String[] args) {
ObjectEqualityTest objectEqualityTest = new ObjectEqualityTest("Java");
ObjectEqualityTest objectEqualityTestOne = new ObjectEqualityTest("Java");
ObjectEqualityTest objectEqualityTestTwo = objectEqualityTestOne;
// checks to see if the reference for the objects are the same
boolean exampleVariableOne = objectEqualityTest.equals(objectEqualityTestOne);
boolean exampleVariableTwo = objectEqualityTestOne.equals(objectEqualityTestTwo);
System.out.println(exampleVariableOne);
System.out.println(exampleVariableTwo);
}
}
ObjectEqualityTest.java
package exlcode;
public class ObjectEqualityTest {
private String exampleVariableThree;
public ObjectEqualityTest(String exampleVaraibleThree) {
this.exampleVaraibleThree = exampleVaraibleThree;
}
}
The default method for objects only checks whether two objects have the same reference. It does not look at the values of the objects inside the reference to see if those are the same. Therefore, it will work exactly the same as the "==" operator. That is why exampleVariableTwo returns "true" as the reference of the two variables is the same. Even though objectEqualityTest and objectEqualityTestOne have the exact same statement with the same parameters, it returns "false" because they are two individual objects.
The way to handle this issue in your own work is to create your own equals() method in your class and override the default one. We will learn how to override methods later in the course.