0
0
Javaprogramming~15 mins

Syntax for command line arguments in Java

Choose your learning style8 modes available
menu_bookIntroduction
Command line arguments let you give information to a program when you start it. This helps the program do different things without changing its code.
You want to tell a program which file to open when it starts.
You want to set options like verbose mode or debug mode when running a program.
You want to pass numbers or words to a program to process without typing them inside the code.
You want to run the same program with different inputs quickly from the command line.
regular_expressionSyntax
Java
public class MyProgram {
    public static void main(String[] args) {
        // args is an array of Strings holding command line arguments
    }
}
The main method must be public and static with String[] args parameter.
Each word or group of characters separated by space in the command line becomes one element in args array.
emoji_objectsExamples
line_end_arrow_notchPrints the first command line argument passed to the program.
Java
public class Hello {
    public static void main(String[] args) {
        System.out.println("First argument: " + args[0]);
    }
}
line_end_arrow_notchPrints how many command line arguments were given.
Java
public class CountArgs {
    public static void main(String[] args) {
        System.out.println("Number of arguments: " + args.length);
    }
}
line_end_arrow_notchPrints all command line arguments, one per line.
Java
public class PrintAll {
    public static void main(String[] args) {
        for (String arg : args) {
            System.out.println(arg);
        }
    }
}
code_blocksSample Program
This program greets the first argument if given, otherwise it greets a stranger.
Java
public class Greet {
    public static void main(String[] args) {
        if (args.length > 0) {
            System.out.println("Hello, " + args[0] + "!");
        } else {
            System.out.println("Hello, stranger!");
        }
    }
}
OutputSuccess
emoji_objectsImportant Notes
line_end_arrow_notch
If no arguments are given, args array is empty but never null.
line_end_arrow_notch
Accessing args elements without checking length can cause errors.
line_end_arrow_notch
Arguments are always Strings; convert them if you need numbers.
list_alt_checkSummary
Command line arguments are passed as a String array to main method.
Use args.length to check how many arguments were given.
Access arguments by index like args[0], args[1], etc.