2.12. Defining and Running Java Programs
A Java program consists of a set of interacting class definitions. But not every Java class or Java file defines a program. To create a program, you must define a class that has a special method with the following signature:
public static void main(String args)
This main( ) method is the main entry point for your program. It is where the Java interpreter starts running. This method is passed an array of strings and returns no value. When main( ) returns, the Java interpreter exits (unless main( ) has created separate threads, in which case the interpreter waits for all those threads to exit).
To run a Java program, you run the Java interpreter, java, specifying the fully qualified name of the class that contains the main( ) method. Note that you specify the name of the class, not the name of the class file that contains the class. Any additional arguments you specify on the command line are passed to the main( ) method as its String[ ] parameter. You may also need to specify the -classpath option (or -cp) to tell the interpreter where to look for the classes needed by the program. Consider the following command:
% java -classpath /usr/local/Jude com.davidflanagan.jude.Jude datafile.jude
java is the command to run the Java interpreter. -classpath /usr/local/Jude tells the interpreter where to look for .class files. com.davidflanagan.jude.Jude is the name of the program to run (i.e., the name of the class that defines the main( ) method). Finally, datafile.jude is a string that is passed to that main( ) method as the single element of an array of String objects.
There is an easier way to run programs. If a program and all its auxiliary classes (except those that are part of the Java platform) have been properly bundled in a Java archive (JAR) file, you can run the program simply by specifying the name of the JAR file:
% java -jar /usr/local/Jude/jude.jar datafile.jude
Some operating systems make JAR files automatically executable. On those systems, you can simply say:
% /usr/local/Jude/jude.jar datafile.jude
See Chapter 8 for details.