When we write the following code in Java:
object1 == object2;
on what basis does the operator '==' decide equality?
When we write the following code in Java:
object1 == object2;
on what basis does the operator '==' decide equality?
If object1
and object2
are reference types, then ==
checks if object1
and object2
are both references to the same object.
See 15.21 Equality Operators in the Java Language Specification for full details.
object1 == object2; will return true if both are reference to same object. Don't assume that it will return true if both objects has same contents or both are objects of same class, etc.
True when both references to same object, false otherwise.
Object a = new Object();
Object b = new Object();
System.out.println(a==b); //not the same
Object c = new Object();
Object d = c; // d points to the same reference
System.out.prinlnt(c==d); // the same