0
0
Javaprogramming~15 mins

Accessing arguments in Java

Choose your learning style8 modes available
menu_bookIntroduction

Arguments let you give information to a program when you start it. Accessing arguments means reading that information inside the program.

You want to tell a program which file to open when it starts.
You want to give a program a number to use in calculations.
You want to change how a program works without changing its code.
You want to pass a username or password to a program at start.
You want to run the same program with different settings easily.
regular_expressionSyntax
Java
public static void main(String[] args) {
    // args is an array of Strings
    String firstArgument = args[0];
}

args is an array holding all arguments as strings.

You access each argument by its position, starting at 0.

emoji_objectsExamples
line_end_arrow_notchThis prints the first argument given to the program.
Java
public class Example {
    public static void main(String[] args) {
        System.out.println("First argument: " + args[0]);
    }
}
line_end_arrow_notchThis prints all arguments one by one.
Java
public class Example {
    public static void main(String[] args) {
        for (int i = 0; i < args.length; i++) {
            System.out.println("Argument " + i + ": " + args[i]);
        }
    }
}
code_blocksSample Program

This program checks if any arguments were given. If yes, it prints how many and lists each one.

Java
public class AccessArguments {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("No arguments provided.");
        } else {
            System.out.println("You gave " + args.length + " arguments.");
            for (int i = 0; i < args.length; i++) {
                System.out.println("Argument " + i + ": " + args[i]);
            }
        }
    }
}
OutputSuccess
emoji_objectsImportant Notes
line_end_arrow_notch

If you try to access an argument that does not exist, the program will crash with an error.

line_end_arrow_notch

Arguments are always strings. You need to convert them if you want numbers.

line_end_arrow_notch

Use args.length to know how many arguments were given.

list_alt_checkSummary

Arguments are extra information given when starting a program.

You access arguments inside main using the args array.

Always check how many arguments you have before using them.