Java Compiler Java Virtual Machine

270 Chapter 9 • Platform Independent Development with Java

9.5 Building Java Applications

A Java application is a compiled Java program that can be executed using a Java virtual machine. There are three basic steps to create a Java application. These steps are:

1. Create source code. 2. Compile it.

3. Run it using the virtual machine.

Let’s see how you can go through these steps.

9.5.1 Creating Source Code File

Like any other programming language, Java source code files are created using an editor. These source code files contain Java instructions. The simplest source code file contains an instruction to print the message “Hello World”, similar to your first C program. Please note that Java examples in this chapter are just to demonstrate how to use development tools. The program that prints the “Hello World” message is shown below: class HelloWorld { public static void mainString[] args { System.out.printlnHello World; } } The program must have a function main, like C programs. The program may be saved as HelloWorld.java text file. Note that you can use any editor to create the source code file. I would recommend using Emacs which you have already learned in Chapter 2. Emacs understands Java programming lan- guage syntax. There are other GUI editors and integrated development environment IDE pack- ages that you can use to create Java source code.

9.5.2 Compiling Java Code

The Java compiler will compile the Java code into an executable. The following command creates an output file HelloWorld.class from source code file HelloWorld.java. usrjavaj2sdk1.4.0binjavac HelloWorld.java Note that the output file name is the same as the name of the class that contains function main. You can check the type of the output file type by using the file command. The following command shows type of the output file as compiled class data. [rootdesktop root] file HelloWorld.class HelloWorld.class: compiled Java class data, version 46.0 [rootdesktop root]