Search code examples
javanullpointerexception

Why doesn't equals throw NullPointerException when one of the variables is pointing to null


Let's consider following code:

String s1=null;
String s2="something";
System.out.println(s2.equals(s1));
//output: false

Why is s2.equals(s1) not throwing NullPointerException?

EDIT: Thanks for the Answers, I am sorry for the Question I wasn't aware of this

For any non-null reference value x, x.equals(null) should return false.

The confusion came because toString method was throwing exception while equals didn't and I thought to myself but equals has also to "look" inside of the object so that it can perform comparison why isn't equals also throwing excetion


Solution

  • It's because the contract for the equals method, as specified in the Javadoc for the Object.equals method , explicitly states:

    For any non-null reference value x, x.equals(null) should return false.

    If the method threw a NullPointerException, it would be non-compliant with the contract.