Junior — Middle
What happens if, when calling the equals method, the object being compared to is null?
sobes.tech AI
Answer from AI
When calling the equals method, if the object being compared is null, the method should return false. According to the contract of the equals method in Java, any object is not equal to null.
For example, a standard implementation of equals often begins with a check:
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
// further checks
}
Failing to include such a check may lead to a NullPointerException when calling methods on obj (for example, obj.someMethod()). Therefore, a correct implementation always considers the possibility of null and returns false.