+ 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

2nd May 2019, 6:29 AM
Daniels Nicole
Daniels Nicole - avatar
3 ответов
+ 7
It has parameters in case you will run your program from command line. Like that:" java MyProgram arg0 arg1" and so on.
2nd May 2019, 6:44 AM
Dima Makieiev
Dima Makieiev - avatar
+ 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
2nd May 2019, 11:55 AM
{ 𝄋 ℒ 𝄋 }
{ 𝄋 ℒ 𝄋 } - avatar
+ 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]...)
2nd May 2019, 3:45 PM
hamza belmellouki
hamza belmellouki - avatar