Skip Top Navigation Bar

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

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.

LocalDate Class Equals Method

boolean equals(Object obj)

This method returns

Comparing LocalDate Objects Tracing


Your Turn

Let's try it in the Java Playground.

Next Learn Tutorial