Reputation: 368
So when we are comparing objects, 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. On the other hand,
String a = null;
return a == null
we would get true. Why is that?
Upvotes: 0
Views: 1530
Reputation: 310980
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.
Upvotes: 5
Reputation: 2812
Additionally,
String s1 = new String("test");
String s2 = "test";
String s3 = null;
Check:
s1 instanceof String // true, s1 is String object and we allocated a memory to it.
s2 instanceof String // true, s2 is String object and we allocated a memory to it.
s3 instanceof String // false, because we did not allocate memory to object of String s3
s1 == null // false, we allocated a memory to the String object s1
s2 == null // false, we allocated a memory to the String object s2
s3 == null // true, because even though s3 is of reference type String, it is null
Note:
s3 instanceof null // Invalid: as instanceof checks from class name. null is not a class
Upvotes: 0
Reputation: 36
I think null represents a variable that does not point to anything in the heap memory。So, if a = null, then a == null returns true is justified,because a does not point to anything, and also null.
Upvotes: 2
Reputation: 140525
Because two different references can point to the same content. Then the objects are equal, but the references are still different.
But when the references are the same, then we'll, there is only one reference.
Given your example:
Object o = new Object();
Object o2 = o;
return o == o2
would result in?!
Upvotes: 4