Conditional Statements With Arguments
The following application will accept two command line arguments, place them in variables x and y, and
print out a statement declaring which is larger.
The variables are initialized at the start of the program. Java allows you to declare and
initialize the variables by parsing the command line arguments on the same line.
A discussion of Java classes, methods, objects and properties will occur later in the tutorial but the statement "Integer.parseInt(args[0])" is an interesting example of how Java works. We are referring to the Integer object and using the method "parseInt" to change the string in args[0] into an integer. Until we learn more about Java classes, we can simply think of "Integer.parseInt(args[0])" as a function that returns the integer of the command line argument.
Copy the following code into a text editor and
save it as compare2.java.
| class compare2 { public static void main (String args[]){ int x = Integer.parseInt(args[0]); int y = Integer.parseInt(args[1]); System.out.println("x ="+ x ); |
Line 2 sets up an array to accept all command line arguments in arg[0]
through arg[n] where there are n arguments on the command line. Lines 3 and 4 declares x and y as integer variables and initializes x equal the first command line argument & y to the second. All command line arguments are strings. For that reason we need to call the parseInt function to convert the strings to Integer values. Line 5 & 6 print out the values for x & y as in the last program. Line 7 sets up the condition if x is less than y we print x is smaller Otherwise print y is smaller |
After compiling this program run it by typing
java compare2 <first command line parameter> <second command line parameter>
Be sure to enter two integers for the command line parameters.
The output should resemble the following.
x =<first command line parameter> y =<second command line parameter> x is smaller ! (or y is smaller ! depending on the input)
x and y values are set to equal the first and second command line parameters. Any extra parameters are ignored.
If we want to compare other values we simply need to enter those as command line parameters. For example if we were to enter.
java compare2 500 100
the output would be
x =500
y =100
y is smaller !
Remember that Java programs can accept any number of string arguments as command line parameters. They will be contained in an array as args[0] args[1] args[2] ....
The next section on loops will demonstrate a program that displays all command line parameters.
Go to the next topic: Loops