0
0
Javaprogramming~15 mins

Why command line arguments are used in Java

Choose your learning style8 modes available
menu_bookIntroduction

Command line arguments let users give information to a program when they start it. This helps the program work differently without changing its code.

When you want to let users choose a file to open without changing the program.
When you want to set options like 'verbose mode' or 'debug mode' before running the program.
When you want to pass numbers or words to the program to process, like a calculator program.
When you want to run the same program with different inputs quickly from the command line.
regular_expressionSyntax
Java
public static void main(String[] args) {
    // args is an array of strings holding command line arguments
}

args holds all the words typed after the program name in the command line.

Each word is a separate string in the args array.

emoji_objectsExamples
line_end_arrow_notchThis prints the first word typed after the program name.
Java
public static void main(String[] args) {
    System.out.println("First argument: " + args[0]);
}
line_end_arrow_notchThis prints all the command line arguments one by one.
Java
public static void main(String[] args) {
    for (String arg : args) {
        System.out.println(arg);
    }
}
code_blocksSample Program

This program checks if any command line arguments were given. If yes, it prints how many and what they are.

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

If you run the program without any arguments, args.length will be zero.

line_end_arrow_notch

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

list_alt_checkSummary

Command line arguments let users give input to programs when starting them.

They help programs behave differently without changing code.

Arguments are accessed as strings in the args array in main.