Why don't we get an error when we don't pass any command line arguments?
We can give p开发者_如何转开发arameter args[]
to the main()
method or choose not to. But if we would call any other parameterized method without passing enough arguments, it would give us an error.
Why it is not the case with the main(String[] args)
method?
public static void main(String[] args)
main
always receives its parameter, which is an array of String
. If you don't pass any command-line arguments, args
is empty, but it's still there.
An array of String is always passed, even if no command line parameters are present. In that situation the length of the array is 0, which you can test for yourself via
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("no parameters were passed");
}
}
As you see, main excepts one function argument - which is an array of strings. JVM takes care of passing any command line arguments as an array of strings to the main function. If there are no arguments given, an empty array is passed - but it's still there.
You could as well have your own function defined as this:
void myMain(String args[]) {
for(int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
}
You can then call this function, emulating passing three command-line arguments:
String a[] = {"foo", "bar", "bah"};
myMain(a);
Or you can emulate situation where no command-line arguments are given:
String a[] = {};
myMain(a);
You can also pass args
from the real main to your function and it will work regardless if any parameters were given or not:
public static void main(String[] args) {
myMain(args);
}
Note that there's no null pointer check in myMain
so if you pass it a null
it will throw NPE.
Java calls the main method itself with arguments, so there is no error on it even though we "call" without arguments.
Because Main
is special and automatically takes an empty String array
in leu of nothing being given. As that accurately describes calling main()
without arguments. The system provides this as a convenience.
I think above answers have captured enough information that args is always received with value.
So, I try to explain slightly in programming way.
Imagine in this way, when there is not argument passed into the command line
its like calling main(null) then args = null;
when there is argument passed into command line args = 'passed value';
Therefore, even when there is no argument passed into it, it still can be executed.
there
精彩评论