-4

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

2 Answers2

1

Usually, the equals implementation has something like:

if ( o == null ) return false;

So, why would you expect this to throw an NPE? If you want it to throw one, change your statement to:

System.out.println( s1.equals(s2)); 

Then, you are actually calling an instance method on a null without checking for null first.

Stultuske
  • 9,296
  • 1
  • 25
  • 37
0

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.

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79