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
true if the value of this String is the same as the String value of anObject. NOTE: All classes extend the Object class, meaning a String is an Object.
false if the value of this String is not the same as theString value of anObject.
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
true if the value of this LocalDate has the same date as obj.
false if the value of this LocalDate does not have the same date as obj.
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.
Next Learn Tutorial