How to pass argument in main function of java program using command line argument
How to pass argument in main function of java program using command line argument
There are only one way to pass argument in main() function of java program and that is using command line .Here is the step by step procedure of how to pass argument using command line.As main function have a formal parameter i.e., args[] which is array of String type and accepts number of arguments passed during the run time of program through command line.
This is illustration of program to calculate the sum of number passed by user as argument in main function.
public class CommandLine
{
public static void main(String []args)
{ int sum=o;
for(int i=0;i<args.length;i++)
{sum=sum+Integer.parseInt(args[i]);
/* Here the argument accepted from command line are added one by one.But there is problem as command line arguments are of String type ,Hence we need to convert them before adding which have been done using Integer.parseInt() function
*/
}
System.out.println("Sum="+sum);
}
}
Then we compile file using javac command as below and the output will be look like--
Explanation:
- First of all go to the directory where file is save as usual you do to compile and run the file.
- Then compile and run the file.
- You have to pass the number of which you wanted summation by giving spaces at the time of running the program.
- Here we pass five argument namely 2,4,8,5,7 and there is the sum of all the number passed as argument which is 26.
I hope you have understood .However if you have any doubt comment below in comment section.
Comments
Post a Comment