Comparing Objects with the Equals Method
Comparing Objects
If we use == to compare objects, you are comparing whether the variables is referencing the same object. If the variables are referencing the same object, it will evaluate to true, otherwise it will evaluate to false.
If you want to compare whether two different objects have the same content, you will need to use the equals method. The equals method is avaiable for all classes. Not all classes have a specific implementation of the equals method, so you will want to look at the API to see if there is an implementation for the class.
String Class Equals Method
boolean equals(Object anObject)
This method returns
trueif the value of thisStringis the same as theStringvalue ofanObject. NOTE: All classes extend theObjectclass, meaning aStringis anObject.falseif the value of thisStringis not the same as theStringvalue ofanObject.
Often when using String literals to create String object, the compiler will create one String literal object and have each variable being assigned the same String literal value refer to this one object.
Comparing String Literals Tracing
Your Turn
Let's try it in the Java Playground.
- Predict the output.
- Run the code to determine if your prediction is correct.
LocalDate Class Equals Method
boolean equals(Object obj)
This method returns
trueif the value of thisLocalDatehas the same date asobj.falseif the value of thisLocalDatedoes not have the same date asobj.
Comparing LocalDate Objects Tracing
Your Turn
Let's try it in the Java Playground.
- Predict the output.
- Run the code to determine if your prediction is correct.