I have a question about the syntax of the Java main
declaration:
public static void main (String[] args)
Since you can pass a variable number of Strings when invoking the main function, shouldn't this be a variable length argument list rather than an array? Why would a command-line invocation of this method with a list of string parameters even work? (Unless there is behind-the-scenes processing that builds an array with the list of strings and then passes that array to the main method...?) Shouldn't the main declaration be something more like this...? -
public static void main(String... args)
Variable-length arguments, varargs for short, are arguments that can take an unspecified amount of input. When these are used, the programmer does not need to wrap the data in a list or an alternative sequence.
Variable-length argument lists, makes it possible to write a method that accepts any number of arguments when it is called. For example, suppose we need to write a method named sum that can accept any number of int values and then return the sum of those values.
Other arguments for the main method Since the main method is the entry point of the Java program, whenever you execute one the JVM searches for the main method, which is public, static, with return type void, and a String array as an argument.
Java main method accepts a single argument of type String array. This is also called as java command line arguments.
main(String... args)
and main (String[] args)
are effectively the same thing: What you're getting is a String
array. The varargs is just syntactic sugar for the caller.
I guess as you never call main()
from code, it wasn't retrofitted when varargs were introduced.
Edit: Actually, scratch that last sentence. main(String... args)
is perfectly valid syntax, of course. The two styles are completely interchangeable. This works just fine:
public class Test { public static void main(String... args) { System.out.println("Hello World"); } }
You can declare main either way, and it works just fine. There are no "backward compatibility" or "retrofitting" issues. However, readers of your code may find it distracting, and it is unlikely to improve your program in any way.
The Java Language Specification (third edition) section 8.4.1 says that "If the last formal parameter is a variable arity parameter of type T, it is considered to define a formal parameter of type T[]".
The specification for how a Java program starts up is in JLS 12.2, which references chapter 5 of the VM spec. The VM spec section 5.2 says that the VM invokes a public class method "void main(String[])
". Since the VM spec has no concept of variable arity, a main that was declared using "...
" satisfies the requirement.
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