sargas sargas - 1 year ago 61
Java Question

Java 8 varargs on main function signature

I was converting a Groovy codebase into Java and forgot to change

public static void main(String... args) {


public static void main(String args[]) {

and compiled and ran the project all this time only to be surprised only now that this is legal Java 8 code.

I understand that Java 8 Varargs makes it possible for a function to have arbitrary number of arguments, "compacting them into an Array" depending on their position on the method call.

But the way functions with
String... args
String[] args
are called syntactically differently:

void function1 (String[] args) {}
function1({"one", "two", "three"});

void function2 (String... args) {}
function2("one", "two", "three");

So how is
String... args
as legal as
String args[]
when grabbing params from the terminal?


It's been legal since varargs were added to the language, I believe. The syntax for calling them explicitly differs, sure, but command-line arguments are passed in not by other Java code but "magically."

JLS 12.1.4 specifies this:

The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String. Therefore, either of the following declarations is acceptable:

public static void main(String[] args)

public static void main(String... args)