Command Line Arguments in Miranda

Command-line arguments are a common way to parameterize execution of programs. For example, java MyProgram arg1 arg2 uses arg1 and arg2 as arguments to the MyProgram class.

public class CommandLineArguments {
    public static void main(String[] args) {
        // In Java, the program name is not included in the args array
        String[] argsWithProg = new String[args.length + 1];
        argsWithProg[0] = "CommandLineArguments";
        System.arraycopy(args, 0, argsWithProg, 1, args.length);

        // args already contains arguments without the program name
        String[] argsWithoutProg = args;

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

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

To experiment with command-line arguments, it’s best to compile the Java class first.

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

In Java, the main method’s String[] args parameter provides access to command-line arguments. Unlike some other languages, Java doesn’t include the program name as the first argument, so we manually added it to argsWithProg for demonstration purposes.

The System.arraycopy() method is used to create a new array that includes the program name along with the command-line arguments.

We can access individual arguments using normal array indexing, as demonstrated 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.