How to Compare Two Objects with the equals Method in Java
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.
equalsmethod correctly determined
circle1is equal to
circle2. As an exercise, change
ifstatement to test circles that are not equal.