+ 5
Why does the java main method have parameters? (String [] args) what's an example of when and how you might pass values?
Java. Question about main method's parameters
3 ответов
+ 7
It has parameters in case you will run your program from command line. Like that:" java MyProgram arg0 arg1" and so on.
+ 3
You can pass command line arguments (while launching the program from a terminal window, for example) which will be stored in an array of Strings and be accessible for your program. It is not obligatory to do, but it allows more flexibility avoiding you changing the source-code unnecessarily often. Note that it stores the arguments as Strings and you may need to convert them to the corresponding type you need.
Here are some examples how you can pass and access command line arguments:
https://www.javatpoint.com/command-line-argument
+ 3
Those are useful if you want to pass arguments using command line. After compiling the code using (javac MyClass.java) you can then run the program and passing it arguments like (java MyClass arg0 arg1...). In the code you reference those arguments like any typical array (args[0] args[1]...)