In java main method, what's the purpose of String args[]
in
public static void main (String args[]) ?
In java main method, what's the purpose of String args[]
in
public static void main (String args[]) ?
args[]
is an String
array. So you can pass more than one String
to your method:
args[0] = "Hello";
args[1] = "World";
...
The main method has only one because it's a form for standardisation. Oracle does not know how many arguments a programmer will need and what types of them. For this reason, with the args[]
of type String
you can pass N
arguments to your program. You can then parse it to any primitive type in Java.
Here is an example of passing arguments to an application with Java:
java MyApp arg1 arg2 arg3 arg4 ... argN
Every value passed is separated by spaces and based in the position, you can retrieve and manipulate them, for example, if you need the arg at position 4 and convert it to a double
, you can do this:
String toDouble = args[4];
double numericalValue = Double.parseDouble(toDouble);
Also, this form was thought to pass some parameters to define and configure some behaviour of your application, so with an unique array this can be accomplished.
When you run your program from the command line or specify program arguments in your IDE, those arguments are split by spaces ("hello world" becomes "hello" and "world", for example) and given to your program in the first argument. Even if the other array existed, there would be no use for it.
You are questioning why Java (and at the same time C/C++) Main threads have only two arguments. Java class has a requirement to use the main method defined in the main class. You would see an error otherwise:
"The program compiled successfully, but main class was not found.
Main class should contain method: public static void main (String[] args)."
This is just a Java requirement you need to adhere to (under silent protest if you wish).
As opposed to that, in C/C++/C++11 you need to have an int main
method, but need not have any arugment. i.e. the following is allowed by the C++ main class requirement:
#include <iostream>
int main(void) { return 0; }
Note that in C/C++, you can also pass an integer as argument in the main.
#include <iostream>
int main(int argc){ return 0;}
To summarise, C/C++/Java each have got their own standards which you have to adhere to. You can argue that something isn't right, but as long as you are one of those people who are in the standards committe, I don't think you can change anything much.
A question regarding C main
has been answered here. Also, the necessity of the main method with String[] args has probably been explained here already.