Command Line Arguments in Karel

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.

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 other languages, the first element
        // of args is the first argument, not the program name.
        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 Java file 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 receives the command-line arguments as a String array (args). Unlike some other languages, the program name is not included in this array. We’ve added it manually to argsWithProg for demonstration purposes.

The System.arraycopy() method is used to create a new array that includes the program name as the first element, followed by the command-line arguments.

Next, we’ll look at more advanced command-line processing with option parsing libraries in Java.