Java Compiler Tutorial

Cay S. Horstmann

Purpose of this Lab

Selecting the right tool for the job is an important task for all computer scientists. As you know, no one tool is appropriate for all circumstances. A Swiss army knife is a great general-purpose tool, but at times, a scalpel or a chainsaw does a better job.

. . .

In this lab, you will learn four (!) different ways of compiling and running a Java program. As you work through the lab exercises, think about the advantages and drawbacks of each method. By the end of the lab, you may have a personal favorite that you want to use for your routine programming tasks. Just as importantly, you will have been exposed to a variety of tools that are valuable in different circumstances.

Checking the JDK Installation

To compile and run Java programs on your computer, you need to have a working installation of the Java Development Kit (JDK) from Sun Microsystems. The JDK includes command-line commands to compile and run Java programs.

You launch these commands directly from the Windows command shell that you encountered in the Windows lab.

Exercise 1
Open a command shell window. Describe what you did to open it.


Exercise 2
In the command shell window, type the command
javac -version

What output did you get?

If the output of the javac -version command starts with a version number such as

javac 1.5.0_04

then your computer already has the Java Development Kit installed.

It is ok if the version number is later than 1.5.0, but if it is earlier, then you need to install a newer version of the JDK.

{short description of image} NOTE: The Java version numbering scheme is a bit of a mess, thanks to the geniuses in Sun's marketing department. Java 5 is internally numbered as 1.5. In fact, the various versions of Java are officially named Java 1.0, Java 1.1, Java2 SE 1.2, Java2 SE 1.3, Java2 SE 1.4, Java2 SE 5.0, Java SE 6. The SE denotes the “standard edition”. There is a micro edition (ME) for cell phones and other small devices, and an enterprise edition (EE) for servers.

If you get an error message such as "command not found" or "not recognized as an internal or external command, operable program or batch file", check that you typed java correctly. If you did and you still get an error message, then you need to install the JDK.

If you work on a computer in a school lab, the JDK should be properly installed. If the test in Exercise 2 fails, see a lab monitor for assistance. But if you work with your own computer, it is entirely possible that the JDK is not properly installed. In that case, go to Appendix 1 of this tutorial, follow the instructions for installing the JDK, and return here when you are done.

Running The JDK Compiler

In the following exercises, you will compile and run a Java program. You will need to create a working directory and place two Java files into it. If you have problems with these activities, you should review the Windows lab.

Exercise 3
In the command shell window, change to your personal directory. (If necessary, create it.) What commands did you issue?

Exercise 4
Inside your personal directory, create a subdirectory named compilerlab. What command did you issue?

Next, download the files and and place them into the c:\yourname\compilerlab directory. (As always in this tutorial, c:\yourname denotes your personal directory. Be sure to substitute c:\jqsmith or whatever your personal directory is called.)

To download each file, follow these steps:

Exercise 5
Go ahead and download the two files now. Then list the files of the working directory for this lab. What is your directory listing?

Now we are ready to try the compiler. The compiler is invoked with the javac command. You tell the compiler which file or files you want to compile, such as

javac *.java

The last command means "compile all Java files in the current directory".

Exercise 6
Type the command

Then type the command


What files are contained in the current directory?

The Java compiler doesn't execute the Java program—that is the job of the Java virtual machine. However, the Java virtual machine cannot execute .java files directly. The compiler's job is to translate Java source files into “class files” that the virtual machine can execute.

If you compile a Java source file and there are no compilation errors, the Java compiler produces one or more “class files” with extension .class. In our example, you should have obtained two class files: CashRegisterTester.class and CashRegister.class.

{short description of image} NOTE: The Java compiler is smart enough to compile all source files that are needed by the source files that you specify. For example, the CashRegisterTester class requires the CashRegister class. When you compile, the compiler automatically compiles (Be sure, however, that you save all your Java files before compiling. If your editor contains a change that you didn't save to disk, the Java compiler can't know about it.)

Now we are ready to execute the Java program. You start the Java virtual machine with the java command, followed by the class that contains the main method. In our case, you issue the command

java CashRegisterTester

CAUTION CAUTION: The javac command takes file names as input. The java command takes a class name, without the .java or .class extension.

CAUTION CAUTION: If the javac command works but the java command fails with a "class not found" error, then you need to fix the CLASSPATH setting. This is sometimes a problem on Windows systems, when a poorly written installer makes a global change to this setting. (QuickTime is the most common culprit.) Follow the description of setting the PATH in the Java/Windows installation at the end of this tutorial. In addition to adding the Java directory to the PATH, add the string
to the beginning of the value of the CLASSPATH environment variable. (The . denotes the current directory, and ; is the separator between directories.)

Exercise 7
Execute the CashRegisterTester class. What is the output?

You now know how to compile and execute a Java program with the JDK command line tools.

Editing and Compiling Programs with a Text Editor

You can create and modify Java source files with a text editor. There are many text editors available. In this tutorial, we use TextPad, a powerful and inexpensive text editor for Windows. If your computer does not have TextPad installed, see Appendix 2 for instructions.

{short description of image} NOTE: Textpad is a shareware program. You are free to install the program and try it out. If you like it and want to use it on your own computer, you need to pay a small fee (about $30) to the author.

linux penguin NOTE: If you use Linux or Mac OS X, or if you don't want to pay the shareware fee for Textpad on your own computer, you can install an open-source text editor. A popular choice for computer scientists is Emacs. Emacs has the somewhat undeserved reputation for being hard to use. The installation is tricky, but the flexibility and power of Emacs is unmatched. See Appendix 3 for instructions.

CAUTION CAUTION: It is a very bad idea to use Notepad, WordPad, or Word for editing Java source files. These programs are not designed for editing program files. They can insert formatting instructions that confuse the Java compiler, change file extensions, or wreck your programs in other ways. It is possible to overcome these problems, but it plainly isn't worth the effort. Install a text editor instead.

Exercise 8
Start TextPad and load the files and How did you carry out these tasks?


You can now edit the files. But before editing them, it is a good idea to adjust the tab settings in TextPad. You don't want TextPad to save your file with tabs. Since the number of spaces per tab is a user-settable value, there is a good chance that your grader, your instructor, or your printer (or all three) have different tab settings. The remedy is to make sure that your editor replaces tabs with spaces.

Select Configure -> Preferences from the TextPad menu. In the resulting dialog, click on the tree nodes Document Classes -> Java -> Tabulation. Then make sure the check boxes Convert new tabs to spaces and Convert existing tabs to spaces when saving files are both set. Also change the default tab spacing and indent size to 3. This matches the settings in your textbook.


Exercise 9
Edit the file so that it prompts the user for the prices and the payment. Add these instructions:
Scanner in = new Scanner(;
System.out.println("Price for first item:");
double price1 = in.nextDouble();
System.out.println("Price for second item:");
double price2 = in.nextDouble();
System.out.println("Payment amount:");
double payment = in.nextDouble();

Now modify the program to use these values. What is your program now?

Exercise 10
Recompile your program, by running the javac program again. Exactly what error messages do you see? (They may be different from those in the image below.)

Chances are that your program didn't compile correctly because you didn't include the statement import java.util.Scanner;. (If you did include the statement, pat yourself on the back, temporarily remove it, and repeat the preceding exercise.)


The compiler error messages show up in the shell window. To fix the errors, you would need to note the line numbers and match them with the corresponding lines in the program. This is a tedious business, but fortunately, your text editor can help.

Exercise 11
In TextPad, select the Tools -> Compile Java menu option or hit the Ctrl+1 key combination. Now TextPad runs the Java compiler on your behalf, captures its output, and shows you the error messages in a window.

Exactly what error messages do you see? (They may be different from those in the image below.)


If you double-click on one of the error messages in the editor window, the editor will move the cursor to the line that contains the error.

linux penguin NOTE: If you use Emacs, use the JDE -> Compile menu option or hit the Ctrl-C Ctrl-V Ctrl-C keystroke sequence to compile your program.

Exercise 12
Add the statement
import java.util.Scanner;

to the top of the file. Fix any other errors that you may have made. Recompile your program inside the text editor by hitting Ctrl+1.

How can you tell that your program compiled correctly?

Once your program compiles without errors, you can also run it from inside your editor. Select the Tools -> Run Java menu option or hit the Ctrl+2 key combination. The editor runs the java command on your behalf.


Exercise 13
Run the program from inside the text editor, by hitting Ctrl+2. Supply inputs 5.99, 10.10, and 20.

What is the result, and where is it displayed?

You now know how to use the text editor for compiling and running simple Java programs.

{short description of image} NOTE: When you work on your homework, you should make a separate directory for each homework assignment. You can make a directory with the mkdir shell command that was described in the first lab.

Using BlueJ

BlueJ is a wonderful environment for learning about Java and object-oriented programming. BlueJ makes it simple to explore objects without the tedium of public static void main.

To start BlueJ, first see whether there is a desktop icon or a start menu option to launch BlueJ. If not, you need to know the directory in which BlueJ is installed. Open a command shell and type a command such as

cd \bluej

On Linux/Unix, enter a command such as

cd /usr/local/bluej

The details depend on your software installation.

When you launch BlueJ for the first time, you get the following window:


Loading an existing program

If you already have your program in a Java file (or a directory containing multiple Java files), then you need to make a project that contains the file. Follow these steps.

Select Project->Open Non BlueJ from the menu.


In the file dialog, select the directory containing your Java files. Do not select the individual files. For example, the following dialog selects the cashregister directory.


Click on the Open in BlueJ button.

Now you see the class or classes that BlueJ discovered in the selected directory.


Click the "Compile" button to compile all classes.

Exercise 14
First, erase all .class files in your compilerlab directory. Then start BlueJ and use the Open Non BlueJ option to load the files in the compilerlab directory. Click the Compile button.

When a class is compiled, the BlueJ display looks different from the preceding figure. What is the difference?

Investigating Objects

The biggest difference between BlueJ and traditional development environments is that BlueJ isn't concerned with running programs. Instead, you investigate objects.

Click on a class rectangle with the right mouse button. You see all of its constructors and static methods.


To instantiate an object, select an appropriate constructor. A default name is offered for the object, and you can change it if you like.


The object is created on the "object workbench" below the class display.

To investigate the object, right-click on it and pick a method.


If the method has parameters, you will get a dialog such as this one:


CAUTION CAUTION: If a parameter has type String, remember to enter the quotes ". . .".

If the method returns a value, you get a dialog that displays it. For example, here is the result of calling the giveChange method:


Exercise 15
Try the steps that were shown on the preceding screens. What change do you get if you follow the steps exactly?

Exercise 16
Which method calls do you need to carry out to get the change displayed in the preceding screen?

Exercise 17

Why is the result not exactly 0.05?

Exercise 18
Now run a more complex example. A customer purchases items for $3.95, $9.95, and $0.50 and pays $20. How much change is due? Report the result that the giveChange method reports, even if it has a roundoff error.

{short description of image} NOTE: Lazy people love to use BlueJ to test their classes. Testing is easy in BlueJ since you don't have to write a separate tester class.

Investigating Library Classes

With BlueJ, you can investigate library classes just as easily as your own classes. Suppose you want to know more about the Rectangle class. Select Tools->Use Library Class from the menu. Type the name of the class (including the package name).


Then hit the ENTER key. You will see a list of all constructors and static methods of the class.


Select the constructor that you want and click Ok. Fill in any construction parameters. The object is created on the workbench. Right-click on it, and you can invoke any of its methods.


Exercise 19

In BlueJ, construct a rectangle with x, y, width, and height set to 5, 10, 15, and 20. Then invoke the translate method with parameters 10 and 20. Afterwards, invoke the getX, getY, getWidth, and getHeight methods. What values do you get?

Exercise 20
Construct a second rectangle on the BlueJ workbench with x, y, width, and height set to 20, 20, 20, and 20. Then invoke the intersection method to compute the intersection between the two rectangles. Place the intersection back on the workbench and invoke its toString method. What result do you get?

Hint: When you invoke the intersection method, you need to specify a Rectangle parameter. Simply click on the rectangle object in the workbench.

If you find it tiresome to use the mouse for manipulating objects, you may enjoy the interaction pane of BlueJ. The interaction pane lets you execute Java expressions without having to write complete programs. Here is an example: computing the square root of 2:


You can also reference any objects in the workbench.

Exercise 21
What happens when you execute the expression rectangl1.getLocation() in the interaction pane?

How can you get a better display of the result? (Hint: toString.)

If the result of a computation in the interaction pane is an object, it has a small red icon to the left. You can drag the icon onto the workbench and manipulate it.


Eclipse is an integrated development environment for Java programming. Eclipse contains many tools that are required for professional Java programming. Moreover, Eclipse has a plug-in architecture that enables you to add additional tools for specialized needs. Eclipse is complex and powerful—think of it as the Swiss Army Chainsaw for Java programming. Fortunately, it is easy to use Eclipse for simple tasks if you are willing to ignore 90% of the menu options and buttons.

Starting Eclipse

When you start Eclipse, a startup screen appears, and the program spends some time loading various modules.


When Eclipse has finished loading, you see a screen similar to the following:


Setting preferences

It is a good idea to set preferences for the Java editor that match the conventions of the textbook. Select Window->Preferences from the menu. Select Java->Appearance->Code Style -> Formatter from the tree in the left panel. Click on New. When prompted, enter your name for the name of the style. Click Ok and a dialog box appears.

Click the Indentation tab and make the following settings:


Click on the Braces tab. Set all brace positions to Next Line.


Click the OK button to save your settings.

Exercise 22
What happens on the right hand side of the Braces dialog when you change the various brace positions?

Loading an existing program

If you already have your program in a Java file (or a directory containing multiple Java files), then you need to make a project that contains the file. Follow these steps.

Select File->New->Project from the menu. You will get the following dialog.


Select the Java Project option and click on the Next> button. (Do not select the Simple option!)

In the following dialog, give a name to the project. A good choice for the name is the directory that contains the files.

Then uncheck the Use default box, and provide the full path of the directory that contains the files, such as





Click on the Finish button.

The project appears in the left hand panel. Click on the triangle to expand it, and also expand the default package icon. Double-click on one of the file names. The file is displayed in an edit window:


Exercise 23
Go ahead and make a project with the files in the compilerlab directory. After loading the project, what steps do you carry out to edit the file?

Compiling a program

To compile a program in Eclipse, you need to do absolutely nothing! Eclipse automatically compiles your code whenever you save a file (with the File -> Save command). It even checks for some errors as you type, similar to the spell checker of a word processor.

If you make a mistake, then an error is displayed both inside the editor pane and the Problems tab at the bottom of the screen.


Exercise 24
Introduce an error in the CashRegister program: spell classs with three s. Save the file. Then mouse over the (x) mark next to the code line with the bug. What happens?

Exercise 25
Go ahead and introduce 10 different errors, 5 in each file! How can you quickly navigate to all of them?

Running a program

To run a program, go to the Package Explorer window on the left hand side of the screen. Right-click on the class that contains the main method (such as CashRegisterTest). Select the Run as...->Java Application menu option. The program runs. Console input and output happen in a window at the bottom of the screen.

To run the same program again, simply select the Run -> Run Last Launched menu option.


Exercise 26
Modify the CashRegisterTester program so that it prompts the user for the costs of three purchased items and the customer payment. Print out the change due. Then run your program with purchase values 19.95, 9.95 and 17.29. The customer payment is $60. What is the content of the entire console window (not just the last line) after your program has completed?

Starting a new program

If you write a program from scratch, then you can start your work in Eclipse. It is always best to place each of your programs into a separate directory.  Eclipse will create the directory for you.

Select File->New->Project from the menu. You will get the New Project dialog.

Select the Java Project option and click on the Next> button. (Do not select the Simple option!)

In the following dialog, give a name to the project. A good choice for the name is the directory that contains the files. Then uncheck the Use default box, and provide the full path of the directory that contains the files, such as





Click on the Finish button. Now locate the name of your new project in the left hand panel. Click on it with the right mouse button. Select New->Class from the menu.


TheNew Class dialog appears.

Supply the name of the class. If you want a main method for this class, check the box public static void main(String[] args).


Click on the Finish button.

Finally, you get an editor window into which you can type your program.


As you type in your program, occasionally select File->Save from the menu to save your work.

Exercise 27
Pretend that your first homework assignment is to write a Java program that prints a message "Hello, Eclipse!" Use the "new class" wizard to create a class in an appropriate directory, then fill in the details. What is the complete code of the program? Include the comments that Eclipse generates automatically.

Exercise 28
What do you do to run your program? Where do you see the output?

Eclipse Tricks

A fancy development environment such as Eclipse has many tools that make your programming tasks easier. In this section, we only introduce a couple of nifty Eclipse tricks. You will see more in an advanced Eclipse lab.

You will probably enjoy the "content assist" feature of Eclipse. If you type a partial input and then hit CTRL+SPACE, a dialog shows all possible completions. Just pick the one you want from the list.


Exercise 29
Type in System.o (that is, the class name System, a period and the letter o). Then hit CTRL+SPACE. What happens? Why?

Exercise 30
Type the following line into your Hello program.

JOptionPane.showMessageDialog(null, "Hello, Eclipse");

  • You will get a wiggly underline under JOptionPane. Why?
  • Now select the menu option Edit -> Quick Fix or simply hit CTRL+1. You will get a list of suggestions for fixing the error. Which one should you accept?
  • What happens when you accept it?

Exercise 31
Switch back to the file. Select the menu option Source -> Generate Getters and Setters. Study the dialog and try out some options. Then describe the purpose of this command.


You have now seen four ways of compiling your Java programs:

  1. The JDK
  2. A text editor with Java integration (e.g. TextPad)
  3. BlueJ
  4. Eclipse

Each of them has different advantages and disadvantages. For example, the JDK is tedious to use. But testing that the JDK works properly is essential for troubleshooting. After all, if the JDK is missing or misconfigured, no other Java tool will work either.

Eclipse is very powerful and has lots of nifty features. It is a favorite choice of professional programmers, but it can be intimidating for the beginner. Many beginners start with a simpler tool and switch to Eclipse when their programs get more complex.

Exercise 32
Give one advantage and one disadvantage each for using
  • A text editor with Java integration
  • BlueJ

Exercise 33
Which tool will you use for your next homework assignment? Why?

There is no “right” answer to this question. Think about what you learned in this lab. Which tools did you like, and which did you hate? Which tool seemed easy to learn? Is it worth for you to learn an easy tool first even though you'll have to eventually learn the harder one anyway? Ponder these issues and form an opinion for yourself.

Appendix 1: Installing the JDK on Windows

  1. Go to and look for a Download link.
  2. On the download page, you may see several versions of the JDK. Pick the latest one (In 2006, it is called JDK 5.0.)
  3. You will see a page with numerous download choices. You want the Java Development Kit (JDK) without the NetBeans environment, and without the Enterprise Edition. Click on the Download link.
    (In 2005, the marketing geniuses at Sun started labeling the most current version "Update n", such as JDK 5.0 Update 6. That's the one you want. It is the full JDK, not an update to an existing installation.)
  4. Select the Windows installer (either the online or offline version are fine). Download and run the installation program.
  5. When the installation program starts, it gives you a chance to change the installation location. As always, you should not accept the default in the Program Files directory. Instead, click on the Change button. Carefully remove Program Files\Java\ from the installation directory, so that the installation directory looks similar to c:\jdk1.5.0\. Make a note of the exact name of the directory.
  6. Continue with the installation. After the JDK has been installed, you are invited to install other features (a runtime environment and additional fonts). You can safely skip these features by clicking the Cancel button.
  7. When the installation is finished, you need to restart the computer (hey, it's Windows).
  8. Open a command shell and type in the command
    c:\jdk1.5.0\bin\java -version

    However, be sure to change the first part jdk1.5.0 to match the exact name of the download directory.

    You should get a message that describes the version of the Java installation. If you get that message, close the shell window and go on to the next step. Otherwise, carefully check the name of the installation directory.

  9. Now comes the part that everyone hates. Click on the Start button and launch the Control Panel. Select the Performance and Maintenance category. Then select the System dialog. In the dialog, click on the Advanced tab:

    Now click on the EnvironmentVariables button.
    In the System variables list, select the Path variable and click the Edit button.
    Carefully click on the Variable value field so that the entire path is no longer highlighted. If you accidentally erase it, hit Cancel right away and try again. Move the cursor to the beginning of the line. Add an entry to the beginning of the field. The entry has the form

    c:\JDK directory name\bin;

    Be sure you enter the exact name of the JDK directory and follow it by \bin; (a backslash, the word bin and a semicolon). Click Ok three times.

  10. Start a new command shell and type
    java -version

    You should now get a version message. Congratulations! You have reached the next level.

linux penguin NOTE: If you use Linux, download the Linux installer that ends in .bin (and not the one that ends in .rpm). Save it in a temporary directory. Open a command shell, change to the temporary directory and type a command such as

sh jdk-1_5_0_04-linux-i586.bin

(Use the name of the file you just downloaded—it will be slightly different, depending on the JDK version). Accept the license agreement. The installer will unpack the JDK into a subdirectory whose name matches the JDK version, such as jdk1.5.0_04. Move that directory to a permanent location (such as /usr/local or, in a pinch, your home directory). Then edit or create a file .bash_profile in your home directory (note that the file name starts with a dot). At the end, add a statement such as

export PATH=/usr/local/jdk1.5.0_04/bin:$PATH

Of course, you need to replace /usr/local/jdk1.5.0_04 with the exact path into which you installed the JDK. Leave the rest (/bin:$PATH) unchanged, and carefully pay attention to the colon and the dollar sign. Save your file.

Start a new command shell and type

java -version

Apple logo NOTE: If you use Mac OS X, a version of Java is already installed on your machine. It may not be the latest one, though. Go to to find out if a later version is available.

Appendix 2: Installing TextPad

Follow the instructions at the TextPad site.

Appendix 3. Installing Emacs (Optional)

  1. Follow these basic installation instructions for Emacs
  2. Make a directory c:\emacs-packages (Windows) or ~/emacs-packages (Linux/Mac OS X) and a misc subdirectory
  3. Download the latest versions of the following packages:
  4. Look inside the emacs-packages directory and note the exact version numbers of the CEDET and JDEE libraries.
  5. Save the following file as c:\emacs\_emacs (Windows; note the underscore) or ~/.emacs (Linux/Mac OS X; note the dot). Replace path with c:\emacs (Windows) or /home/yourname (Linux/Mac OS X), where yourname is your login name. Edit the version strings to match the versions that you observed in the preceding step.
    (setq load-path
    (require 'cua)
    (CUA-mode t)
    (require 'cedet)
    (require 'jde)

That wasn't so bad, was it? The CUA mode package supplies Windows-style selection (with shift + cursor keys) and cut/copy/paste commands. The JDEE mode package lets you compile and run Java programs. Emacs has lots of keyboard shortcuts, but you can learn them one at a time--they are marked on the menus. Just remember that C means Ctrl and M means Alt (or Meta in Emacs-speak).


Appendix 4: Installing BlueJ

Go to and download the correct file for your operating system. Then go to and follow the installation instructions.

Appendix 5: Installing Eclipse

  1. Go to
  2. Select the download site for Java Development Tools. You do not want the Plugin Development Tools or the naked Eclipse Platform.
  3. Select the latest release build (3.1 as of Summer 2005)
  4. Select the archive (.zip or .tar.gz) for your platform (Windows, Linux GTK [not Motif] or Mac) and download it.
  5. Expand the archive into a temporary directory. You get a directory tree that starts with eclipse
  6. Move that directory into a folder such as c:\ or /usr/local or (in a pinch) your home directory
  7. Locate the executable program called eclipse inside the eclipse folder, and execute it.