Image

Java - Core Java - Command line argument

Command line argument

Command Line Arguments can be used to specify configuration information while launching your application. There is no restriction on the number of java command line arguments. You can specify any number of arguments Information is passed as Strings.

They are captured into the String args of your main method

When we wish to pass the String array, we simply include the elements of the array as simple Strings beside the class name. Enclosing the Strings in quotes is optional. Consecutive Strings are separated with a space.

For example, if we wish to pass a three element String array containing the values "1", "2", and "3" any of the following lines is entered on the command prompt.

java Add 1 2 3 
java Add "1" "2" "3"

Since these arguments are passed through the command line, they are known as command line arguments. The String arguments passed are stored in the array specified in the main() declaration. args[] is now a three element String array. These elements are accessed in the same way as the elements of a normal array. The following is the complete Add program which is capable of adding any number of integers passed as command line arguments.

Program to add numbers by accepting arguments from command line
public class Addition {
    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("The sum of the arguments passed is " + sum);
    }
}
Output
D:\javap>java Addition 3 2 1 5 6
The sum of the arguments passed is 17