Java object equals | Sololearn: Learn to code for FREE!

0

Java object equals

I don't understand why does it works like this. It says that references are compared, but 2nd output is false String name = "James"; Animal a1 = new Animal(name); Animal a2 = new Animal(name); Animal a3 = new Animal("James"); System.out.println(a3 == a2); //false System.out.println(a1 == a2); //false name = "James"; a2 = a1; a1.name = "John"; a3 = a1; System.out.println(a3 == a2); //true

12/1/2016 7:53:09 AM

WDRed

2 Answers

New Answer

+3

Whenever you create an instance of a class (using "new"), you're creating *separate* instances, which point to different memory addresses, thus making that the == comparison yields false (the system actually compares the memory addresses). But when you assign an instance to another one (as in "a2=a1"), you're actually making that the memory address of a1 is stored into a2 --that is, both a1 and a2 contain the same memory address, thus the comparison == yields true.

+2

when you create some object from a class and assign each one a new reference, well, as you say comparing them with the others with (==) always returns false because you allocated each one a unique reference (new) and the (==) just comparing the reference of objects. as the same way when you use assignment on objects, the left one points to the right one and due a reference can't point to more than one object, but an abject can has different references, so after that you assigns "a1" object to others, this will happen: "a1" has two new reference "a2" and "a3" and you can't access "a2" and "a3" objects because their reference left them. and they(references a2 and a3) are pointing to an other object else (a1). now when you comparing them with (==), it returns true because both of them are pointing to a1 so their references are equal.