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 - srcand- bindirectory, then create the- .javafile for a class called- ArgTesterand place- ArgTester.javain the- srcdirectory.- cs1302-cla ├── bin └── src └── ArgTester.java
- In - ArgTester.java, add the declaration for the- ArgTesterclass.
- In your - ArgTesterclass, add the following- mainmethod:- 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 to- mainbut you’ve probably never used it. That parameter is a reference to an array containing the command-line arguments.
- Compile the - ArgTesterclass, specifying- binas the destination directory.- javac -d bin ArgTester.java 
- Run - ArgTesteras usual using the- javacommand. Here is what the command looks like with the expected program output, assuming you are running it from the- cs1302-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 the- argsarray 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 standard- mainmethod 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.