Monday, December 26, 2011

Executing a Java Application

To execute the bytecode program in the .class file with the Java interpreter in the JDK, you make the directory containing the .class file current and enter the command:

java -enableassertions MyProgram

Note that we use just the name MyProgram to identify the program, not the name of the file generated by the compiler, MyProgram.class. It is a common beginner’s mistake to use the latter by analogy with the compile operation. If you put a .class file extension on MyProgram, your program won’t execute, and you will get an error message:

Exception in thread “main” java.lang.NoClassDefFoundError: MyProgram/class

While the compiler expects to find the name of your source file, the java application interpreter expects the name of a class, which is MyProgram in this case, not the name of a file. The MyProgram.class file contains the MyProgram class. We will explain what a class is shortly. The -enableassertions option is necessary for JDK 5.0 programs that use assertions, and since you will be using assertions once you have learned about them it’s a good idea to get into the habit of always using this option. You can abbreviate the -enableassertions option to -ea if you wish. If you want to override an existing CLASSPATH definition, the option is the same as with the compiler. You can also abbreviate -classpath to -cp with the compiler or the Java interpreter. Here’s how the command would look:

java -ea -cp . MyProgram

To execute your program, the Java interpreter analyzes and then executes the bytecode instructions. The Java Virtual Machine is identical in all computer environments supporting Java, so you can be sure your program is completely portable. As we already said, your program will run just as well on a Unix Java implementation as it will on that for Microsoft Windows, Solaris, Linux, OS/2, or any other operating system that supports Java.

No comments:

Post a Comment

Thanks for Commenting......