THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

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 argument 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 following output:


in here


The name of the class is not included in the strings passed to main. You already know the name because it is
the name of the class in which main is declared.


An application can have any number of main methods because each class in the application can have one.
Which class's main method is used is specified each time the program is run, as Echo was.


Exercise 2.18: Change Vehicle.main to create cars with owners whose names are specified on the
command line, and then print them.


2.11. Native Methods


If you need to write a program that will use some existing code that isn't written in the Java programming
language, or if you need to manipulate some hardware directly, you can write native methods. A native
method lets you implement a method that can be invoked from the Java programming language but is written
in a "native" language, usually C or C++. Native methods are declared using the native modifier. Because
the method is implemented in another language, the method body is specified as a semicolon. For example,
here is a declaration of a native method that queries the operating system for the CPU identifier of the host
machine:


public native int getCPUID();

Free download pdf