Java Reference
In-Depth Information
CAUTION
One thing the quotation marks are not used for is to identify
strings. Every argument passed to an application is stored in an
array of String objects, even if it has a numeric value (such as
450, -10, and 49 in the preceding examples).
Handling Arguments in Your Java Application
When an application is run with arguments, Java stores the arguments as an array of
strings and passes the array to the application's main() method. Take another look at the
signature for main() :
public static void main(String[] arguments ) {
// body of method
}
Here, arguments is the name of the array of strings that contains the list of arguments.
You can call this array anything you want.
Inside the main() method, you then can handle the arguments your program was given
by iterating over the array of arguments and handling them in some manner. For exam-
ple, Listing 5.4 is a simple Java program that takes any number of numeric arguments
and returns the sum and the average of those arguments.
LISTING 5.4
The Full Text of Averager.java
5
1: class Averager {
2: public static void main(String[] arguments) {
3: int sum = 0;
4:
5: if (arguments.length > 0) {
6: for (int i = 0; i < arguments.length; i++) {
7: sum += Integer.parseInt(arguments[i]);
8: }
9: System.out.println(“Sum is: “ + sum);
10: System.out.println(“Average is: “ +
11: (float)sum / arguments.length);
12: }
13: }
14: }
The Averager application makes sure that in line 5 at least one argument was passed to
the program. This is handled through length , the instance variable that contains the
number of elements in the arguments array.
 
Search WWH ::




Custom Search