Reading command line arguments

Java:
Reading command line arguments

How to:

Java scoops up command line arguments you dish out with the main method. Look at this bite-sized sample:

public class CommandLineExample {
    public static void main(String[] args) {
        // Let's print out the command line arguments
        for(String arg : args) {
            System.out.println(arg);
        }
    }
}

Fire up your terminal, compile with javac CommandLineExample.java, and run with java CommandLineExample These Are Command Line Arguments. Here’s your output:

These
Are
Command
Line
Arguments

Deep Dive

Originating from C, command line arguments have been a staple since the dark ages of programming—think punch cards and timesharing. Java inherited this utility for good reason. It’s elementary, versatile, and fits a range of situations.

Highly alternative? Sure, there’s plenty. Libraries like JCommander or Apache Commons CLI beef up your parsing prowess. They handle more complex scenarios with finesse.

Under the hood, Java’s main method snags a String array—args. In the virtual machine run, when you hit java ClassName, what follows are your inputs, neatly stored in args.

See Also: