This section describes the Java program entry point, the main() method of the starting class. Command line arguments are passed as an string array parameter to the main() method.
As mentioned in the previous section, a Java application program must have
a starting class with a special method call main() as the execution entry point.
The main() method must be defined as follows:
public static void main(String[] a) {
// statement block
}
Note that the main() method is a class method, defined as "static". So when it
is called by the JVM, no instance of the starting class will be created.
The parameter of the main() method is an array of "String", which contains the
additional arguments after the class name argument in the "java" command line.
Let's use the following Java program to illustrate how those arguments are
passed into the main() method:
/**
* CommandLine.java
* Copyright (c) 2002 by Dr. Herong Yang
*/
class CommandLine {
public static void main(String[] a) {
System.out.println("Number of arguments = "+a.length);
for (int i=0; i<a.length; i++) {
System.out.println(" a["+i+"] = "+a[i]);
}
}
}
After compiling the class, execute it with the following command line:
c:\jdk\bin\java -cp . CommandLine bread milk banana apple
Number of arguments = 4
a[0] = bread
a[1] = milk
a[2] = banana
a[3] = apple
4 arguments are specified in the command line after the class name.
The JVM put them in an array of 4 elements and pass the array as
a parameter to the main() method.
Execute it again with a slightly different command line:
c:\jdk\bin\java -cp . CommandLine "bread milk" "banana apple"
Number of arguments = 2
a[0] = bread milk
a[1] = banana apple
This time, double quotes are used to make two space delimited words as
a single argument.