Command Line Arguments in Java makes us to pass the arguments to the program while execution. In this module we will learn more about Java Command Line Arguments with examples. Before diving into command line arguments kindly have a look at Java Operators.
Table of Contents
[hide]Java Command Line Argument excepts arguments at the time of executing a Java program. The argument which we will pass will be provided to the Java main function. String array in the main function accepts this arguements.
If you are not aware about java main method, just have a look at our Java-simple-program module where we have discussed the syntax of a simple java program.
You can pass any number of java command line arguments while executing a Java Program. These arguements are passed as strings to the java main method.
// Java program to illustrate Java Command Line Argument.
public class CommandLineExample{
public static void main(String args[]){
System.out.println("First argument is: " + args[0]);
System.out.println("Second argument is: " + args[1]);
}
}
// Java program to calculate sum of numbers
public class CommandLineExample{
public static void main(String args[]){
int sum = 0;
for( int i=0 ; i< args.length ; i++){
sum = sum + Integer.parseInt(args[i]);
}
System.out.println("Sum is: " + sum);
}
}
You can provide any number of inputs, in above program I have calculated the sum with three numbers, you can calculate the sum of n.. numbers. Hope you have got the basic understanding of Command Line Arguments in Java.