4.3. Command-Line Arguments Tutorial

Let’s try to use the args parameter in Java!

  1. Create a directory for this tutorial called cs1302-cla, then change into it.

  2. Create a src and bin directory, then create the .java file for a class called ArgTester and place ArgTester.java in the src directory.

    cs1302-cla
    ├── bin
    └── src
        └── ArgTester.java
    
  3. In ArgTester.java, add the declaration for the ArgTester class.

  4. In your ArgTester class, add the following main 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
    
  5. 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 to main but you’ve probably never used it. That parameter is a reference to an array containing the command-line arguments.

  6. Compile the ArgTester class, specifying bin as the destination directory.

    javac -d bin ArgTester.java
    
  7. Run ArgTester as usual using the java command. Here is what the command looks like with the expected program output, assuming you are running it from the cs1302-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).

  8. 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 the args 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 standard main method is used to capture command-line arguments and make them available to the program.

  9. 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"
    
  10. 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.