What is the advantage of the "equals"-method over using the point notation in comparison of values? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What is the advantage of the "equals"-method over using the point notation in comparison of values?

Can somebody please explain to me, why we need the "equals" method? Isn't it possible to access and compare the attributes of two instances of the same class by using the point notation (see example code below)? What is the advantage of the "equals"-method? Example Code: public class MyClass { public static void main(String[ ] args) { class Animal { String name; Animal(String n) { name = n; } } Animal a1 = new Animal("Robby"); Animal a2 = new Animal("Robby"); System.out.println(a1 == a2); System.out.println(a1.name == a2.name); } } // output of first comparison: false // output of second comparison: true

6th Jan 2017, 12:50 PM
Christian Wiesner
2 Answers
+ 3
Basically equals does the exact same thing like you did in your second SOUT. Equals compares the Member-Variables while the == operator compares the place where your object is allocated in your RAM.
6th Jan 2017, 1:38 PM
Jonas Fallmann
Jonas Fallmann - avatar
+ 1
equals method would be less lines of code and more efficient as well as easier to read
7th Jan 2017, 1:54 AM
Earl Chukwu
Earl Chukwu - avatar