Wednesday 2 March 2016

Running Java Applications

A standalone Java application must have at least one class containing a method called main(), which is the first code to be executed upon startup. To run the application, start the VM, specifying that class as an argument. You can also specify options to the interpreter as well as arguments to be passed to the application:

 % java [interpreter options] class_name [program arguments]  
The class should be specified as a fully qualified class name, including the package name, if any. Note, however, that you don’t include the .class file extension. Here are a couple of examples:
 %java things.livingthings.Man  
 %java SimpleCalculator  
The interpreter searches for the class in the classpath, a list of directories and archive files where classes are stored. We’ll discuss the classpath in detail in the next section. The classpath can be specified either by an environment variable or with the commandline option -classpath. If both are present, the command-line option is used. Alternately, the java command can be used to launch an “executable” Java archive (JAR) file:
 % java -jar spaceblaster.jar  
In this case, the JAR file includes metadata with the name of the startup class containing the main() method, and the classpath becomes the JAR file itself. After loading the first class and executing its main() method, the application can reference other classes, start additional threads, and create its user interface or other structures, as shown in this figure.
The main() method must have the right method signature. A method signature is the set of information that defines the method. It includes the method’s name, arguments, and return type, as well as type and visibility modifiers. The main() method must be a public, static method that takes an array of String objects as its argument and does not return any value (void):
 public static void main ( String [] myArgs )  
The fact that main() is a public and static method simply means that it is globally accessible and that it can be called directly by name. We’ll discuss the implications of visibility modifiers such as public and the meaning of static. The main() method’s single argument, the array of String objects, holds the commandline arguments passed to the application. The name of the parameter doesn’t matter; only the type is important. In Java, the content of myArgs is an array. In Java, arrays know how many elements they contain and can happily provide that information:
 int numArgs = myArgs.length;  
myArgs[0] is the first command-line argument, and so on. The Java interpreter continues to run until the main() method of the initial class file returns and until any threads that it has started also exit. Special threads designated as daemon threads are automatically terminated when the rest of the application has completed.

0 comments:

Post a Comment