Passing arguments to a program
Passing arguments to a program is one way to make your programs more generic. Arguments passed to a program let the same compiled code behave differently based on the values provided at runtime.
As a simple example, consider a program that needs to add together two values passed to it. This program will assume that the arguments are both integers:
package adder;
public class Adder {
public static void main(String[] args) {
int i1 = Integer.valueOf(args[0]);
int i2 = Integer.valueOf(args[1]);
int result = i1+i2;
System.out.printf("The result is %d", result);
}
}
If you run this program like the ones you have run up until this point it will fail. This is due to the fact that the args array has zero elements and the program attempts to access elements at position 0 and 1.
When you run this program, you need a way to provide arguments to it. In order to demonstrate this, right click on the class in the package explorer view and choose Run As -> Run Configurations…
This will present you a dialog. Choose the Arguments tab, and enter two numbers (separated by a space) in the Program arguments box, as shown in figure 7-2:
Figure 7-2
If you now choose Run at the bottom of the dialog, the program will print out the result of adding the two numbers.
Once you learn more about looping through arrays you will appreciate that it is possible for a program to accept and process an arbitrary number of parameters. For instance, you may let the user pass as many numbers as they want, and have the program add them all together.