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
30Numbers 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:
hihihihihiFlags
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 0Check args.length and print a hint on how to run the program.
Functions used in this recipe
- Integer.parseInt() — Converts a string containing an integer to an int.
- String.startsWith() — Checks whether a string starts with the given prefix.