Command Line Arguments in Logo

Our first program demonstrates how to use command-line arguments. Here’s the full source code:

import java.util.Arrays;

public class CommandLineArguments {
    public static void main(String[] args) {
        // args provides access to raw command-line arguments.
        // Note that unlike in some languages, the program name itself
        // is not included in the args array in Java.
        String[] argsWithProg = new String[args.length + 1];
        argsWithProg[0] = "CommandLineArguments";
        System.arraycopy(args, 0, argsWithProg, 1, args.length);
        
        String[] argsWithoutProg = args;

        // You can get individual args with normal indexing.
        String arg = args[2];

        System.out.println(Arrays.toString(argsWithProg));
        System.out.println(Arrays.toString(argsWithoutProg));
        System.out.println(arg);
    }
}

To experiment with command-line arguments, it’s best to compile the program first and then run it with arguments:

$ javac CommandLineArguments.java
$ java CommandLineArguments a b c d
[CommandLineArguments, a, b, c, d]
[a, b, c, d]
c

In Java, command-line arguments are passed to the main method as an array of strings. Unlike some other languages, the program name itself is not included in this array. We’ve simulated the behavior of including the program name in argsWithProg for demonstration purposes.

The args array directly corresponds to the command-line arguments passed to the program. You can access individual arguments using array indexing, as shown with arg = args[2].

Next, we’ll look at more advanced command-line processing with flags, which in Java is typically done using libraries like Apache Commons CLI or JCommander.