Java Reference
In-Depth Information
2.10. The
main
Method
Details of invoking an application vary from system to system, but
whatever the details, you must always provide the name of a class that
drives the application. When you run a program, the system locates and
runs the
main
method for that class. The
main
method must be
public
,
static
, and
void
(it returns nothing), and it must accept a single argu-
ment of type
String[]
. Here is an example that prints its arguments:
class Echo {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++)
System.out.print(args[i] + " ");
System.out.println();
}
}
The
String
array passed to
main
contains the
program arguments.
They
are usually typed by users when they run the program. For example, on
a command-line system such as
UNIX
or a
DOS
shell, you might run the
Echo
application this way:
java Echo in here
In this command,
java
is the Java bytecode interpreter,
Echo
is the name
of the class, and the rest of the words are the program arguments. The
java
command finds the compiled bytecodes for the class
Echo
, loads
them into a Java virtual machine, and invokes
Echo.main
with the program
arguments contained in strings in the
String
array. The result is the fol-
lowing output:
in here