Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to read command-line arguments

Short answer

Add a String[] args parameter to main — it holds the words passed after the file name. Run it as java Main.java Anna 30:

void main(String[] args) {
    IO.println("Arguments: " + args.length);
    for (String arg : args) {
        IO.println(arg);
    }
}

Output:

Arguments: 2
Anna
30

Numbers and defaults

Arguments are always strings. Parse numbers yourself and set a default if the argument is missing. Run it as java Main.java 5:

void main(String[] args) {
    int count = args.length > 0 ? Integer.parseInt(args[0]) : 3;
    String word = args.length > 1 ? args[1] : "hi";
 
    IO.println(word.repeat(count));
}

Output:

hihihihihi

Flags

Flags like --verbose and --name=value are checked by how the string starts. Run it as java Main.java --verbose --name=Oleg:

void main(String[] args) {
    boolean verbose = false;
    String name = "World";
    for (String arg : args) {
        if (arg.equals("--verbose")) {
            verbose = true;
        } else if (arg.startsWith("--name=")) {
            name = arg.substring("--name=".length());
        }
    }
    IO.println("Hello, " + name + (verbose ? " (verbose mode)" : ""));
}

Output:

Hello, Oleg (verbose mode)

For complex command-line interfaces there is the picocli library.

Common mistake

Accessing args[0] when the program was started without arguments:

void main(String[] args) {
    IO.println("Hello, " + args[0]);
}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0

Check args.length and print a hint on how to run the program.

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.