You must have now by realised what String[] args within the declaration of the main method means. It represents a String array named args. Since args is nothing more than an identifier, we can replace it with any other identifier and the program will still work. What we need to know now is how a String array can be passed as an argument when we execute the program. We pass it through the command line itself. Consider that we have a class named Add. The following statement normally used to execute the program.
java Add
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.
public class Add {
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);
}
}
Top comments (0)