+ 14
[DUPLICATE] Why exactly does the main method need an array as a parameter?
10 Answers
+ 10
It's possible (especially in command line) to pass a program data when you run it. For instance if you wrote a program that reads a file then displays the contents in some way. You would use those arguments to pass the file ext.
+ 6
The array of string args in the main function is used to store arguments passed to the program. For example, after we compile our java code (ex. named Program.java) by executing
javac Program.java
, then we can run the program (without arguments) by
java Program
But we can also pass arguments to the program by doing it like this
java Program arg1 arg2
arg1 and arg2 are the arguments; they will be stored into args array variable as string, and we can access them from the main function
+ 4
so that it can display result which may cantain more than one integer or words which can be stored in an array.
+ 3
Just to add on the the answers here, this is a form of variadic parameters, which simply means you can provide 0 to many arguments as command-line arguments to your program. This means that you needn't supply any cmdline arguments as in many applications and the main method will still run with no problems and at the same time allow for command line arguments to be supplied wen needed.
+ 2
it's used to store the command line arguments as an array which you pass when u run a program via terminal or command prompt
+ 1
In Windows it would be if you open a file with the program, or drag and drop on the program. Say you're making a notepad program and want to double-click on .txt to open a file. Then, String[] args has the path to your file so you know what to open.
+ 1
Because string args [] are a dynamic way of passing arguments as per our need,as many as we want.
0
because compiler always starts execution from main method and it checks the main keyword and then only starts execution and we can pass values through cmd line only since compiler starts execution from main method it reads arguements first and then go into the method so array is necessary if u need to pass arguements through cmdline
0
bcoz the user can input the value of any length or size and string is the only data type which takes interger character string etc.
- 2
Why void is used