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?
Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of values. This argument that can accept variable number of values is called varargs.
The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows: return_type method_name(data_type... variableName){}
It describes all aspects of the language, including the semantics of all types, statements, and expressions, as well as threads and binary compatibility.
Varargs are useful for any method that needs to deal with an indeterminate number of objects. One good example is String. format . The format string can accept any number of parameters, so you need a mechanism to pass in any number of objects.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With