Reputation: 540
I was wondering how equals method in Object class works. This is the implementation of the method.
public boolean equals(Object obj) {
return (this == obj);
}
where its evident that equals method is using ==
.
So,now when I am comparing two objects a and b, if a happens to be null, it doesn't throw any exception. But a.equals(b)
, throws NPE, why?
Upvotes: 1
Views: 221
Reputation: 397
a.equals(b) throws null pointer exception because a is null, so when you try to call the instance method on a null object it gives a null pointer exception. For more information please refer to the documentation below for null pointer exception. http://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html
For these types of situation you should first check whether a is null and then should use the method on this object.
if(a != null) {
a.equals(b);
}
Upvotes: 0
Reputation: 3339
When you call method on null object, it even doesn't call the method but gives null pointer error on same movement. Same is applicable to equals.
When invoke a.equals(b)
;
It will give null pointer exception as you are calling equals on a which is null.
For example, if you create method blank.
public Class MyClass{
public voidblank() {
}
}
and now even if you call blank on null object it will give you null pointer, nothing to do with method implementation.
MyClass a = null;
a.blank();
This will also give null pointer as a is null.
Upvotes: 1
Reputation: 201537
But a.equals(b), why does it throw NPE?
Because you can't invoke a method on null
(methods are invoked by the referene variable in Java). When a
is null, there is simply nothing to call equals
on (or to de-reference). All that Object
(non-primitive) Java variable types can hold is the value of a reference (or null
, which by definition is not a value). That's why Java (pass by value), has the functionality of pass by reference. The value of Object
(s) are references.
Upvotes: 1