Why does Object == null
work?
This doesn't really mean anything. Objects aren't values in Java. You can't write that. All you can write is someObjectReference == null
.
So when we are comparing objects
We aren't. See above. We are comparing references.
we use equals() methods, or something similar in an if statement for example. If we have the following code
String a = "foo";
String b = "foo";
return a==b
we would get false returned to us because a and b refer to different objects.
No we wouldn't, and no they don't. It will return true. Try it. String literals are pooled by Java. There is only one "foo"
object.
On the other hand,
String a = null;
return a == null
we would get true. Why is that?
Because the value of the reference a
is null, and so is the value of expression on the RHS of the ==
operator. Equal values => result of ==
is true
. Note that a
is a reference, not an object.