why is it mandatory to pass string arg[] as an argument in main method? why we cannot pass any other data type available in java? whats the importance of passing String arg[] in main method in java?
Because by passing String arrays , we can pass all the necessary parameters like options/arguments related to the program in the form of String easily. There can be several parameters! Also, all the other datatypes can be easily converted from String!
The Java runtime system looks specifically for a method with a single String[] type parameter, because it wants to pass the parameters to your main method. If such a method is not present, it informs you through an exception.
If I do not provide any arguments on the command line, then the String array of main() method will be empty or null? It is empty.
Can main() method take an argument other than String array? No, an argument of main() method must be String array. But, from the introduction of var args you can pass var args of string type as an argument to main() method.
History. This is a convention since the days of C, maybe even earlier? Java took most of its syntax from C.
Also, command line arguments are Strings which is why that is the data type. Collections did not exist in Java 1 so they were not an option. Arrays did exist.
Because by passing String arrays
, we can pass all the necessary parameters like options/arguments related to the program in the form of String easily. There can be several parameters!
Also, all the other datatypes can be easily converted from String!
An example of calling a program with several parameters therefore resulting in storage of them in String array!
java Sample_Example example1 example2 example3
Arguments:
args[0]=example1
args[1]=example2
args[2]=example3
Here, you are calling Sample_Example
Class and passing three parameters example1
,example2
and example3
to be used by the program! So, it is always an better alternative to store them in an String array rather than other primitive data-types or in collections or in Wrapper data-types. Always we tend to make our work simpler and here Java makes it simpler for all of us by providing this facility!
The idea is that your Java application will be invoked via a command (whether explicitly entered by a user, implicitly entered (like when you click a shortcut in your OS's GUI), etc).
The String[]
refers to the command line arguments specified when your application was invoked.
See Command-Line Arguments in Oracle's Java tutorials for more details.
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