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
srcandbindirectory, then create the.javafile for a class calledArgTesterand placeArgTester.javain thesrcdirectory.cs1302-cla ├── bin └── src └── ArgTester.javaIn
ArgTester.java, add the declaration for theArgTesterclass.In your
ArgTesterclass, add the followingmainmethod: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[] argsas a parameter tomainbut you’ve probably never used it. That parameter is a reference to an array containing the command-line arguments.Compile the
ArgTesterclass, specifyingbinas the destination directory.javac -d bin ArgTester.java
Run
ArgTesteras usual using thejavacommand. Here is what the command looks like with the expected program output, assuming you are running it from thecs1302-cladirectory:java -cp bin ArgTester
arguments:As you can see, no iterations of the for-loop were executed. This is expected as the
argsarray 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
argsis not empty. That’s right, we’ve used theargsarray 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
argsarray of a standardmainmethod 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
argsarray). Now, experiment by adding some command-line options of your own.