Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't we get an error when we don't pass any command line arguments?

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?

like image 881
shalini satre Avatar asked Sep 06 '11 05:09

shalini satre


3 Answers

 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.

like image 135
Gabriel Negut Avatar answered Sep 20 '22 17:09

Gabriel Negut


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");
   }
}
like image 36
Hovercraft Full Of Eels Avatar answered Sep 21 '22 17:09

Hovercraft Full Of Eels


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.

like image 33
kto Avatar answered Sep 22 '22 17:09

kto