1

Why is Java executing method(char[] a) for method(null) if there is also method(Object a) instead of generating ambiguous method error?


When trying to build a string using the static method String.valueOf()... i face this situation. Please, see the self-explanatory-ready-for-run example below:

public class NotSoClearNullPointerException {

  public static void main(String[] args) {

    NotSoClearNullPointerException instance = new NotSoClearNullPointerException ();
    instance.algo(null);
    String str =  String.valueOf(instance.getANull());
    System.out.println ("This actually is beign send to stdout : " + str);
    str =  String.valueOf(null);
    System.out.println ("We never gonna make it to stdout!! : " + str);


  }

  public Object getANull() {
    return null; // the hardest method i ever wrote... xD
  }

}

After checking the source of the String class, i see that the String.valueOf(Object) method is null-safe!!, so the String.valueOf(null) is not actually calling the String.valueOf(Object) method, instead is calling another overloaded method.. my guess is that calling String.valueOf(char[]), knowing that every array (despite of the base type) is an object.

I am pretty sure of this because i make my own test, again ready-to-run-code-below:

public class ArgumentDispatchExample {

  public static void main(String[] args) {

    ArgumentDispatchExample instance = new ArgumentDispatchExample ();
    instance.method(null);
  }

  public void method (Object a) {
    System.out.println("Object");
  }


  public void method (char[] a) {
    System.out.println("char[]");
  }

}

Assuming that i am right... (this is by the way, part of the question...), i always thought that this invocation must generate an ambiguous error because the compiler doesn't if it must associate the "null" to an Object or to the char[] instance.

Java doesn't support double dispatch (that is resolving what method to invoke inspecting the actual type of the argument), so what kind of rule is using here to make the decision of taking null as char[]? All my life, i thing that null is more close to an Object "thing" that to other kind of abstraction.

To what kind of type is "more" associated a null value?

I eagerly waiting for answers!!

Grettings.

Victor

P.D.: As HPO (Humble personal opinion)... Don't we agree that is kind of confusing, specially if you look at the first example...? Perhaps, this is a good starting point to purpose a debate in the java community. Well, thanks!.

Victor
  • 3,841
  • 2
  • 37
  • 63

0 Answers0