The first step of compiling and running a Java program is to write the text of your program in a document and save it on the hard drive. This document is called a source file, and you must name it with a .java extension. Next, compile this program using a Java compiler. The compiler checks the program for errors and, if no errors are found, it generates a new document containing Java bytecode. This document is called a class file, and its name ends with a .class extension.
Although a processor can run machine code directly, it cannot execute Java bytecode. Instead, a special program called the Java virtual machine (or JVM) is used for this purpose. Unlike processors that are built from hardware components, the JVM is software that does the work of a processor. The JVM contains a class loader that loads the program into memory, and an interpreter that is responsible for executing Java bytecode. The JVM must be installed on the computer where you want to run Java programs. A platform refers to the type of processor and/or the operating system in a computer. Different JVMs are available for different platforms. Figure shows how the program stored in the source file HelloWorld.java is compiled and run.
The advantage of using Java bytecode is that it is portable-that is, you can run the bytecode for a program on any platform that has a JVM installed on it. For this reason, Java is a "compile once, run anywhere" language. On the other hand, programs written in a language such as C or C++ are usually compiled each time they are run on a different platform. The compilers for these languages directly generate machine code for the platform on which the program will be run.