Command Line Arguments in Java

Here’s the translation of the Go code example for command-line arguments to Java, formatted for Hugo:

Our program demonstrates how to work with command-line arguments in Java. Command-line arguments are a common way to parameterize execution of programs.

public class CommandLineArguments {
    public static void main(String[] args) {
        // args provides access to raw command-line arguments.
        // Note that unlike in some languages, args does not include the program name.
        String[] argsWithoutProg = args;

        // We can create a new array that includes the program name if needed
        String[] argsWithProg = new String[args.length + 1];
        argsWithProg[0] = "CommandLineArguments";
        System.arraycopy(args, 0, argsWithProg, 1, args.length);

        // You can get individual args with normal indexing.
        String arg = args[2];  // Be careful: this may throw ArrayIndexOutOfBoundsException

        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 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

Note that in Java, unlike some other languages, the args array in the main method does not include the program name as the first argument. If you need this functionality, you have to add it manually as shown in the example.

Also, be careful when accessing arguments by index. If you try to access an argument that wasn’t provided, Java will throw an ArrayIndexOutOfBoundsException. It’s often a good idea to check the length of the args array before accessing its elements.

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