Chapter 10. Compiling Java

The Java virtual machine was originally designed to run programs written in Java. A Java compiler translates Java programs into class files, which can be executed on any JVM implementation. Although the JVM is equipped with sufficient instructions to handle any language, many instructions are particularly well suited to Java. In particular, it is always possible to compile any valid Java program into a JVM class file that will pass the verification algorithm's checks.

This chapter discusses how Java programs are converted into JVM programs. We look at Java programs from the point of view of a Java compiler (or a Java compiler writer). A complete definition of the Java language in terms of the JVM would stretch to hundreds of pages, so a lot of details must be omitted. The reader can fill in the details.

A simplified view of how a Java compiler sees a Java file appears in Figure 10.1. The input file contains a series of class declarations, which are made up of a series of field and method declarations. Method declarations in turn are made from statements, which are built from expressions. In the forthcoming sections, we look at a Java program from the inside out, starting at expressions and ending with completed class files. The translations are shown in terms of Oolong code. While Oolong is not exactly equivalent to bytecodes, it is extremely close and a lot more readable.

Figure 10.1. Structure of a Java source file

graphics/10fig01.gif

The code shown in this chapter is not necessarily identical to the code generated by any actual Java compiler. The code created by real Java compilers is generally more efficient but less straightforward than the code shown in this book. The class files produced by different Java compilers are different but equivalent from the point of view of the user.

One of the best ways to learn how the JVM works is to compile examples written in Java using a commercial Java compiler such as javac in the Java Development Kit. Then use the Gnoloo disassembler provided with this book to produce a readable version of the class files. You can also use javap with the -c option, which also produces a disassembly of the bytecodes; javap comes with the Java Development Kit.



Programming for the Java Virtual Machine
Programming for the Javaв„ў Virtual Machine
ISBN: 0201309726
EAN: 2147483647
Year: 1998
Pages: 158
Authors: Joshua Engel

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net