4.3. Command-Line Arguments Tutorial¶
Let’s try to use the args
parameter in Java!
Create a directory for this tutorial called
cs1302-cla
, then change into it.Create a
src
andbin
directory, then create the.java
file for a class calledArgTester
and placeArgTester.java
in thesrc
directory.cs1302-cla ├── bin └── src └── ArgTester.java
In
ArgTester.java
, add the declaration for theArgTester
class.In your
ArgTester
class, add the followingmain
method:public static void main(String [] args) { System.out.println("arguments:"); for (int i = 0; i < args.length; i++) { String arg = args[i]; System.out.printf("args[%d] = %s\n", i, arg); } // for } // main
Take a few minutes to carefully read through the code above. Try and understand what it’s doing. Note: Up until this point, you’ve always typed
String[] args
as a parameter tomain
but you’ve probably never used it. That parameter is a reference to an array containing the command-line arguments.Compile the
ArgTester
class, specifyingbin
as the destination directory.javac -d bin ArgTester.java
Run
ArgTester
as usual using thejava
command. Here is what the command looks like with the expected program output, assuming you are running it from thecs1302-cla
directory:java -cp bin ArgTester
arguments:
As you can see, no iterations of the for-loop were executed. This is expected as the
args
array would be empty in this scenario (there are no command-line arguments provided).Now try the following command:
java -cp bin ArgTester one two three
What happened when you ran it? It looks like the for-loop iterated. The array referred to by
args
is not empty. That’s right, we’ve used theargs
array for something! Here’s the expected output:java -cp bin ArgTester one two three
arguments: args[0] = one args[1] = two args[2] = three
In Java, the
args
array of a standardmain
method is used to capture command-line arguments and make them available to the program.Now that we see how to access the command-line arguments in our code, let’s see how different command-line arguments are parsed. Try the following commands:
java -cp bin ArgTester "one two" three
java -cp bin ArgTester --help "some topic"
java -cp bin ArgTester --string "my \"awesome\" day"
That’s it! The rest is purely in the realm of code. We’ve shown you how command-line arguments are passed into a Java program (i.e., via the
args
array). Now, experiment by adding some command-line options of your own.