Skip to content
On this page

Command Line Parameters

The entry point of the Java program is main method, and main method can accept a command line parameter, which is a String[] array.

This command line parameter is received by the JVM and passed to main method:

java
public class Main {
  public static void main(String[] args) {
    for (String arg : args) {
      System.out.println(arg);
    }
  }
}

We can use the received command line parameters to execute different codes based on different parameters. For example, implement a -version parameter to print the program version number:

java
public class Main {
    public static void main(String[] args) {
        for (String arg : args) {
            if ("-version".equals(arg)) {
                System.out.println("v 1.0");
                break;
            }
        }
    }
}

The above program must be executed from the command line, let’s compile it first:

$ javac Main.java

Then, when executing, pass it a -version parameter:

$ java Main -version
v 1.0

In this way, the program can respond differently based on the command line parameters passed in.

Summary

The command line parameter type is String[] array;

The command line parameters are received by the JVM and passed to main method;

How to parse command line parameters needs to be implemented by the program itself.

Command Line Parameters has loaded