How to Compare Two Objects with the equals Method in Java
See Java: Tips and Tricks for similar articles.
To test whether two objects are equal, a developer should provide an equals method. The logic in the method can determine if the two objects are equal and return true, or return false otherwise. To compare two objects with the equals method, follow these four steps.
- Open your text editor and create a new file that will contain the circle class and a
mainmethod to test two circles for equality. Type in the following Java statements.
According to the equalsmethod, two circles are equal if they have the same radius. - Save your file as CompareTwoObjectsWithequalsMethod.java.
- Open a command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter.

- You are ready to test your program. Type in the command to run the Java runtime launcher and then hit Enter.
Notice the equalsmethod correctly determinedcircle1is equal tocircle2. As an exercise, changecircle2tocircle3in theifstatement to test circles that are not equal.
