Java Reference
In-Depth Information
as a separator. It creates an array of String whose length is the same as the number of arguments in the list.
It populates the String array with the items in the arguments list sequentially. Finally, the JVM passes this String array
to the main() method of the Test class that you are running. This is the time when you use the String array argument
passed to the main() method. If there is no command-line argument, the JVM creates a String array of length zero and
passes it to the main() method. If you want to pass space-separated words as one argument, you can enclose them
in double quotes. You can also avoid the operating system interpretation of special characters by enclosing them in
double quotes. Let's create a class called CommandLine as shown in Listing 15-9.
Listing 15-9. Processing Command-line Arguments Inside the main() Method
// CommandLine.java
package com.jdojo.array;
public class CommandLine {
public static void main(String[] args) {
// args contains all command-line arguments
System.out.println("Total Arguments:" + args.length);
// Display all arguments
for(int i = 0 ; i < args.length; i++) {
System.out.println("Argument #" + (i+1) + ":" + args[i]);
}
}
}
Table 15-2 shows the command to run the com.jdojo.array . CommandLine class and the corresponding output.
Table 15-2. Output of Command-line Argument Program Using Different Arguments
Command
Output
java com.jdojo.array.CommandLine
Total Arguments:0
java com.jdojo.array.CommandLine Cat Dog Rat
Total Arguments:3
Argument #1:Cat
Argument #2:Dog
Argument #3:Rat
java com.jdojo.array.CommandLine "Cat Dog Rat"
Total Arguments:1
Argument #1:Cat Dog Rat
java com.jdojo.array.CommandLine 29 Dogs
Total Arguments:2
Argument #1:29
Argument #2:Dogs
What is the use of command-line arguments? They let you change the behavior of your program without re-
compiling it. For example, you may want to sort the contents of a file in ascending or descending order. You may pass
command-line arguments, which will specify the sorting order. If there is no sorting order specified on the command
line, you may assume ascending order by default. If you call the sorting class com.jdojo.array.SortFile , you may
run it in the following ways.
 
Search WWH ::




Custom Search