We can give parameter 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.
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