+ 1

Why main method contains array of strings in its parameter?

19th Nov 2016, 4:34 AM
Avinash Choudhary
Avinash Choudhary - avatar
3 Réponses
+ 4
You may call a java program from the command line of your operating system. For example, you could call a program "sayhello" from a prompt "> java sayhello" and it will run. You can also pass some parameters in it, for example "> java sayhello par1 par2". If you want to get those params into your java program, they are filled into the string array of your main method. So if you declare "public static void main(String[] args)", then inside your main method you'll have args[0]="par1" and args[1]="par2".
19th Nov 2016, 5:20 AM
Álvaro
+ 3
Think, for example, of a java program that takes two input strings and concatenates them. It could look like this: public static void main(String[] args) { System.out.println(args[0]+" "+args[1]); } Then you could call it ">java myProgram Hi there" and the result would be "Hi there". For a more useful case, think of a program that could accept flags to affect its behavior: public static void main(String[] args) { if (args[0]=="-log") { System.out.println("Start logging."); } /* rest of code */ } which you may call by ">java myProgram -log".
25th Nov 2016, 6:45 AM
Álvaro
0
But if we pass two int parameters in main by passing from command prompt what will be output. Means how it affects main. What is use of passing parameters from command prompt in main
19th Nov 2016, 6:40 AM
Avinash Choudhary
Avinash Choudhary - avatar