Java Command-Line Arguments Explained

Java command-line arguments are the text values supplied after the class name when you launch a program.

Lesson 14 of 127Beginner13 min read

Java command-line arguments are the text values supplied after the class name when you launch a program. In the traditional entry point public static void main(String[] args), Java provides them as a String array. The first supplied argument is args[0]; the class name itself is not included.

Arguments are different from interactive input. They arrive when the program starts, making them useful for small tools, file paths and repeatable commands. Validate how many were supplied and interpret their meaning explicitly before using them.

How arguments reach main

For java GreetingTool Ada, the launcher starts GreetingTool and supplies an array containing Ada. With java GreetingTool, the array is empty. The parameter name args is conventional rather than mandatory; another valid identifier works if the method signature otherwise matches.

Arguments are strings even when they contain digits. Supplying 12 does not create an int inside the array. The runtime has not validated a business rule merely by delivering the text. A command such as java GreetingTool Ada B sees two arguments, while quoted multiword text can become one argument according to the shell’s quoting rules. These rules belong partly to the shell, so test commands in the environment where you expect the tool to run.

Check the length before indexing

An empty args array has length zero and no valid index zero. Accessing args[0] without checking can throw ArrayIndexOutOfBoundsException. Write a usage message when required arguments are missing, or choose a documented default when the argument is optional.

For two required values, check args.length against two before reading both. Decide what extra arguments mean: reject them, ignore them deliberately or interpret them as a list. Silently ignoring unexpected text can conceal a user mistake. A concise usage message should name the accepted positions and units, such as quantity and unit-price, instead of only saying Invalid input. Validate count first so later code can safely name the expected positions.

Parse numeric text and validate its meaning

Integer.parseInt converts a valid integer string to int. Noninteger text and values outside the int range cause NumberFormatException. Catch that specific failure when the user should receive a readable input message, rather than a raw stack trace.

Parsing and validation are separate steps. The text -3 is a valid int, but a negative quantity may violate the tool’s rules. After parsing, check the permitted range. Multiplying valid arguments can still overflow, so choose long or checked arithmetic when totals may exceed int. Do not use a cast to convert args[0] to a number: a String is not a numeric primitive, and casting does not interpret its characters.

Optional values and defaults

A useful optional argument has a clear fallback, such as a greeting name defaulting to visitor. Choose the fallback only when the argument is absent, not whenever parsing fails unless that forgiving behavior is explicitly intended. Replacing an invalid supplied value with a default can hide mistakes.

For several options such as --count and --verbose, manual positional parsing can become difficult to maintain. A dedicated argument-parsing library can support named options and help text, but that is beyond these dependency-free beginner programs. Start with a small stable positional contract. Include examples showing no arguments, valid arguments and invalid arguments so a caller can predict both success and failure behavior.

Paths, privacy and reproducible commands

A filename argument is text describing a path, not an automatically opened file. Use Path.of and file APIs to resolve and operate on it. Relative paths usually resolve from the process’s working directory, which may differ from the source file’s directory. State that assumption in a command-line tool’s documentation.

Do not treat command-line arguments as a safe place for secrets. They can appear in shell history or process information, depending on the environment. Use a suitable configuration or secret-management method when security requirements matter. For ordinary lesson examples, keep arguments nonsensitive and include the exact command that produces each output. This makes testing possible without confusing program-generated text with the terminal command used to launch it.

Practice with explained solutions

Task 1. Create a program requiring one name argument and print a usage message when the count is not exactly one.

Solution. Check args.length != 1 before accessing args[0]. Return after the usage message so the protected access cannot run.

Task 2. Describe the difference between parsing "0" successfully and deciding that zero is an acceptable quantity.

Solution. Parsing confirms numeric syntax and range. A separate business rule decides whether zero is allowed, rejected or given a special meaning.

Java Summary

  • Launcher arguments arrive as strings and exclude the launched class name.
  • Check array length before indexing, then parse and validate each value separately.
  • Document optional defaults and shell quoting assumptions in the tool's usage instructions.
  • Continue with input validation.

Java Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Use a default when an argument is absent

Save this complete program as GreetingTool.java. Compile with javac --release 17 GreetingTool.java and run with java GreetingTool.

Java
public class GreetingTool {
    public static void main(String[] args) {
        String name = args.length == 0 ? "visitor" : args[0];
        System.out.println("Hello, " + name);
    }
}
Output
Hello, visitor
Line-by-line explanation
  1. Lines 1 to 6This displayed run uses java GreetingTool with no arguments, so the array length is zero and the default becomes visitor. Running java GreetingTool Ada instead prints Hello, Ada. The length check protects the access to index zero. Additional arguments are deliberately unused in this tiny example; a stricter tool would reject unexpected positions.
Example 2

Require two positions before reading

Save this complete program as QuantityTool.java. Compile with javac --release 17 QuantityTool.java and run with java QuantityTool.

Java
public class QuantityTool {
    public static void main(String[] args) {
        if (args.length != 2) {
            System.out.println("Usage: java QuantityTool quantity unit-price");
            return;
        }
        System.out.println("Quantity text: " + args[0]);
        System.out.println("Unit-price text: " + args[1]);
    }
}
Output
Usage: java QuantityTool quantity unit-price
Line-by-line explanation
  1. Lines 1 to 10The displayed invocation supplies no arguments, so the guard prints a usage message and returns from main. Neither array access executes. Running java QuantityTool 3 4 instead prints Quantity text: 3 and Unit-price text: 4 on separate lines. This version verifies the count but deliberately does not yet parse or validate the values.
Example 3

Parse and reject a negative quantity

Save this complete program as ParsedQuantity.java. Compile with javac --release 17 ParsedQuantity.java and run with java ParsedQuantity.

Java
public class ParsedQuantity {
    public static void main(String[] args) {
        String supplied = args.length == 0 ? "5" : args[0];
        try {
            int quantity = Integer.parseInt(supplied);
            if (quantity < 0) {
                System.out.println("Quantity must not be negative");
                return;
            }
            System.out.println("Quantity: " + quantity);
        } catch (NumberFormatException exception) {
            System.out.println("Quantity must be a whole number in int range");
        }
    }
}
Output
Quantity: 5
Line-by-line explanation
  1. Lines 1 to 8With no arguments, the default text five parses successfully and passes the nonnegative check. Running java ParsedQuantity -2 produces the negative-quantity message.
  2. Lines 9 to 15Running java ParsedQuantity many produces the parsing-error message. These outcomes distinguish missing input, invalid numeric text and a numeric value that violates the domain rule, rather than treating all three as one failure.

Common Java Mistakes

Checking for one argument but reading two

Do not read args[1] merely because args.length is greater than zero; two positions require a length of at least two. Also avoid catching every Exception around the whole program just to label every failure as bad input. Catch expected parsing failures near parsing and let unrelated defects remain distinguishable during development.

Java FAQ

Does args contain the Java class name?

No. It contains the arguments supplied after the launched class name, starting at index zero.

Can an argument contain spaces?

Yes, when the shell passes the text as one argument, usually through appropriate quoting. The exact quoting and escaping rules depend on the shell.

How do I pass command-line arguments in an IDE?

Edit the run configuration. In IntelliJ IDEA, open Run, then Edit Configurations, and type the values into Program arguments. In VS Code, add an args list to the launch configuration. Each space-separated value becomes one element of args, unless it's quoted.

Do arguments work when running a source file directly?

Yes. With java GreetingTool.java Ada "Grace Hopper", everything after the file name is passed to main, so args holds two values: Ada and Grace Hopper. The file name itself isn't included, just as the class name isn't with java GreetingTool.

Should I use a library for command-line options?

For a couple of positional values, plain args is fine. For named options such as --verbose or --output report.csv, with help text and validation, a library such as picocli or Apache Commons CLI saves a lot of code and gives users consistent behaviour.

Java Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choiceeasy

What does java GreetingTool Ada pass at args[0]?

Multiple choicemedium

Why validate a parsed quantity after parseInt?

Java Quiz

2 questions to check what you learned.

  1. What is the type of each args element?

    • String
    • int whenever it contains digits
    • char[]
  2. What must happen before reading args[0] when input may be absent?

    • Check that the array has an element
    • Cast args to int
    • Print every argument twice