Thursday, January 13, 2011

Executing a Java Program

Summary: To run a Java program, the interpreter must be invoked with an argument giving the name of the main method. This module explains the exceptions that can be raised if the name is incorrect.





You can run a Java program from within an environment or by executing the interpreter from the command line:
java Test
where Test is the name of a class containing a main method.
Suggestion: It is convenient to write main methods in most classes and to use then for testing classes individually. After the classes are integrated into a single program, you only need ensure that the interpreter is invoked on the class that contains the “real” main method.
Two runtime errors can occur if the interpreter is not successful in finding and running the program.

NoClassDefFoundError

The interpreter must be able to find the file containing a class with the main method, for example, Test.class. If packages are not used, this must be in the directory where the interpreter is executed. Check that the name of the class is the same as the name of the file without the extension. Case is significant!
Warning! If you are compiling and running Java from a command window or shell with a history facility, you are likely to encounter this error. First, you compile the program:
javac MyClass.java
and then you recall that line and erase the c from javac to obtain the command for the interpreter:
java MyClass.java
Unfortunately, MyClass.java is not the name of the class so you will get this exception. You must erase the .java extension as well to run the interpreter:
java MyClass
If you are using packages, the main class must be in a subdirectory of that name. For example, given:
package project1.userinterface;
class Test {
  public static void main(String[] args) {
    ...
  }
}
the file Test.class must be located in the directory userinterface that is a subdirectory of project1 that is a subdirectory of the directory where the interpreter is executed:
c:\projects> dir
   <DIR> project1
c:\projects> dir project1
   <DIR> userinterface
c:\projects> dir project1\userinterface
   Test.class
The program is invoked by giving the fully qualified name made up of the package names and the class name:
c:\projects> java project1.userinterface.Test

NoSuchMethodFoundError: main

This error will occur if there is no method main in the class, or if the declaration is not precisely correct: the static modifier, the void return type, the method name main written in lower case, and one parameter of type String[]. If you forget the public modifier, the error message is Main method not public.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...

java

Popular java Topics