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). ...

Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.