+ 1

Why the output 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); } }

1st Aug 2018, 6:08 AM
ADITYA SINHA
ADITYA SINHA - avatar
4 Antworten
+ 1
== on objects will check if they are the same object not just same values. To just compare values do a1.equals(a2)
1st Aug 2018, 6:47 AM
JME
0
Jason Edelson thankyou
1st Aug 2018, 7:41 AM
ADITYA SINHA
ADITYA SINHA - avatar
0
Try a2 = a1 and than compare it using a1 == a2.
1st Aug 2018, 7:49 AM
Meet Mehta
Meet Mehta - avatar
0
Because two objects are different even they have same value. But if you pass reference of one object to another they will be same as they both are referring to same content and answer will be true. Its very little info but hope it helps☺️☺️.
1st Aug 2018, 7:53 AM
Meet Mehta
Meet Mehta - avatar