Comparing object. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Comparing object.

can someone explain to me why this method is FALSE? class Animal { String name; Animal(String n) { name = n; } } class MyClass { public static void main(String[ ] args) { Animal a1 = new Animal("Robby"); Animal a2 = new Animal("Robby"); System.out.println(a1 == a2); } }

30th Oct 2021, 4:23 PM
discard_fourcmd
discard_fourcmd - avatar
1 Answer
+ 2
1. Point: Equals for OBJECTS means "the same object" But you have two differend objects. 2. If you do it like this: Animal a1 = new Animal("Robby"); Animal a2 = a1; System.out.println(a1 == a2); Then you will get true, Because it's only one object in two differend variables. 3. To compare objects, you should use the .equals() method. a1.equals(a2) 4. Why is .equals() better? Because you can override the equals method of your class, and define when two objects of this class should be equal or not. https://www.baeldung.com/java-comparing-objects
30th Oct 2021, 5:19 PM
Coding Cat
Coding Cat - avatar