Java Reference
In-Depth Information
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 com-
mand-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 .
7.13.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 inte-
ger 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Ā 7.12 shows sample runs of the program.
The strings passed to the main program are stored in args , which is an array of strings. The
first string is stored in args[0] , and args.length is the number of strings passed.
Here are the steps in the program:
1. Use args.length to determine whether the expression has been provided as three
arguments in the command line. If not, terminate the program using System.exit(1) .
2. Perform a binary arithmetic operation on the operands args[0] and args[2] using the
operator in args[1] .
Add
Subtract
Multiply
Divide
F IGURE 7.12
The program takes three arguments ( operand1 operator operand2 ) from
the command line and displays the expression and the result of the arithmetic operation.
 
 
Search WWH ::




Custom Search