Overloading methods and passing ‘null’ as argument

Posted by Martin Homik | Posted in Java | Posted on 28-10-2008

2

Today, I came across a NPE which pointed me to a problem which I cannot resolve. Assuming, you have two overloaded methods in a class:

  1. public void setProperty(Collection c);
  2. public void setProperty(String c);

Which method will be invoked when the parameter is null?

Answer: you cannot call setProperty with a null parameter. The compiler will complain. In all other cases the signature of the method is matched. So, it doesn’t matter if your String has the null value, it only matters that you apply a method applied to a String parameter. This is the signature. This is matched.