Reputation: 129337
I am looking for a relevant portion of the Java Language Specification (JLS) which describes the behaviour when invoking a variable arity (vararg) method.
Consider the method:
public static void printVarArgs(String... args) {
System.out.println(Arrays.toString(args));
}
If I invoke the method like so:
printVarArgs();
The output will look like: []
because the omission of args
at the call site has been converted into an empty array in the printVarArgs
method.
I am looking for the point of the JLS which defines this behaviour. The closest I have found is 15.12.4.2 Evaluate Arguments, but it doesn't give this example, and I'm not sure if this case is actually covered by the formal/mathematical description.
Which part of the JLS describes the automatic creation of an empty array when a vararg is omitted?
Upvotes: 6
Views: 897
Reputation: 719386
The text of that JLS section says:
If the method being invoked is a variable arity method (§8.4.1)
m
, it necessarily hasn > 0
formal parameters. The final formal parameter ofm
necessarily has typeT[]
for someT
, and m is necessarily being invoked withk >= 0
actual argument expressions.If m is being invoked with kn actual argument expressions, or, if m is being invoked with
k != n
actual argument expressions and the type of the kth argument expression is not assignment compatible withT[]
, then the argument list(e1, ... , en-1, en, ...ek)
is evaluated as if it were written as(e1, ..., en-1, new T[]{en, ..., ek})
.
In the case you are talking about, there are k == n - 1
formal arguments, so en, ..., ek
is an empty sequence, and that means the argument is evaluated as if it was (e1, ..., en-1, new T[]{})
.
In other words, the behaviour is specified in the section you were looking at.
Upvotes: 5
Reputation: 189836
From JLS 15.12.4.2:
The final formal parameter of m necessarily has type T[] for some T, and m is necessarily being invoked with k >= 0 actual argument expressions.
That's from the callee perspective. I'm not sure where it states from the caller's perspective the behavior you cite, but it's kind of implied.
Upvotes: 5