Java Reference
In-Depth Information
9.7.1 Passing Strings to the main Method
You can pass strings to a main method from the command line when you run the program.
The following command line, for example, starts the program TestMain with three strings:
arg0 , arg1 , and arg2 :
java TestMain arg0 arg1 arg2
arg0 , arg1 , and arg2 are strings, but they don't have to appear in double quotes on the
command line. The strings are separated by a space. A string that contains a space must be
enclosed in double quotes. Consider the following command line:
java TestMain "First num" alpha 53
It starts the program with three strings: First num, alpha , and 53 . Since First num is a
string, it is enclosed in double quotes. Note that 53 is actually treated as a string. You can use
"53" instead of 53 in the command line.
When the main method is invoked, the Java interpreter creates an array to hold the
command-line arguments and pass the array reference to args . For example, if you invoke a
program with n arguments, the Java interpreter creates an array like this one:
args = new String[n];
The Java interpreter then passes args to invoke the main method.
Note
If you run the program with no strings passed, the array is created with new
String[0] . In this case, the array is empty with length 0 . args references to this
empty array. Therefore, args is not null , but args.length is 0 .
9.7.2 Case Study: Calculator
Suppose you are to develop a program that performs arithmetic operations on integers. The
program receives an expression in one string argument. The expression consists of an integer
followed by an operator and another integer. For example, to add two integers, use this
command:
VideoNote
Command-line argument
java Calculator "2 + 3"
The program will display the following output:
2 + 3 = 5
Figure 9.14 shows sample runs of the program.
The strings passed to the main program are stored in args , which is an array of strings. In
this case, we pass the expression as one string. Therefore, the array contains only one element
in args[0] and args.length is 1 .
Here are the steps in the program:
1. Use args.length to determine whether the expression has been provided as one argu-
ment in the command line. If not, terminate the program using System.exit(1) .
2. Split the expression in the string args[0]
into three tokens in tokens[0] ,
tokens[1] , and tokens[2] .
3. Perform a binary arithmetic operation on the operands tokens[0] and tokens[2]
using the operator in tokens[1] .
 
Search WWH ::




Custom Search