0

Given the void foo(Boolean... bars) function, the value of bars behaves very differently from what it apparently should be on the following function calls:

  • foo(), bars = Boolean[0]
  • foo(null), bars = null
  • foo(null, null), bars = Boolean[2] { null, null }

Why does calling foo(null) yields bars = null instead of Boolean[1] { null }? This was reproduced on Java 8.

Yves Calaci
  • 1,019
  • 1
  • 11
  • 37
  • I would hope you get a compiler warning about that. You're allowed to pass an explicit array to a varargs parameter, and for `foo(null)` it's guessing that that's what you're trying to do. – khelwood Nov 11 '19 at 13:59

1 Answers1

2

This is because of the 3-phase approach to determining method signature:

  1. Identify Matching Arity Methods Applicable by Strict Invocation
  2. Identify Matching Arity Methods Applicable by Loose Invocation
  3. Identify Methods Applicable by Variable Arity Invocation

foo(null) is matched in phase 1, because a single null argument is allowable for a method accepting a Boolean[], because you can cast null to Boolean[] (or, indeed, any reference type).

foo(null, null) is matched in phase 3, because that's when variable arity methods are matched. Assuming you don't have a 2-arg overload of foo, it couldn't be matched before that, because a matching method would require two arguments.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243