2

If I have two methods with the same signature, varying only by vararg type, how does Java know which one to call when I use no parameter or pass null?

For example, if I have these two methods:

public static String test(String a, String b, Object... args){
    return "object args";
}

public static String test(String a, String b, String... args){
    return "string args";
}

And I call:

System.out.println(test("a", "b"));
System.out.println(test("a", "b", null));

The output is "string args". Why does Java decide to call the 2nd method here instead of the first one? I had a hard time finding the relevant portion of the specification that describes this.

Alex Pritchard
  • 4,260
  • 5
  • 33
  • 48
  • 5
    As usual Java picks most specific type for `null` and `String[]` is more specific then `Object[]`. More info: http://stackoverflow.com/questions/13033037/how-is-an-overloaded-method-chosen-when-a-parameter-is-the-literal-null-value – Pshemo Oct 07 '15 at 20:40
  • Ah, the vararg was distracting me from the simpler, more obvious scenario. As referenced in the link to which this is a duplicate: "The String overload here is chosen because the Java compiler picks the most specific overload, as per section 15.12.2.5 of the JLS." Duh. Thanks everyone. – Alex Pritchard Oct 07 '15 at 20:46

1 Answers1

1

As I understand this, String[] is more specific than Object[] and so null is matched to String[]; however,you'll frequently need to cast the null to a type if you're specifically using null. If the argument was typed, you wouldn't have this issue.

test("a", "b", (String)null);

is the same as

String foo = null;
test("a", "b", foo);
Steve Chaloner
  • 8,162
  • 1
  • 22
  • 38