Home CPSC 330

Compiling Java Code

Lab Code

The new after-hours lab code is: 059044.

Java Compilation Model

C++ is compiled from source code directly into machine code that can be run on your computer. Java works differently.

Java code is compiled into byte code. This byte code isn't human readable, but it is not an executable file that can be run directly on the machine.

The byte code is then run by the Java virtual machine which runs the program.


File Names are Important

Unlike C++, the name of files is important in Java. Then name of the file must match the name of the class that it contains.

This program:


public class HelloWorld {                                                                                              
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }   
}

Has to be saved in a file called "HelloWorld.java".


Compiling on the Command Line

Compiling in Java is done with the javac command. Download the hello world program, then run:


> javac HelloWorld.java
This will produce a file called "HelloWorld.class" containing the Java byte code for the program. You can run this on the Java virtual machine with the java command:

> java HelloWorld

Using the Eclipse IDE

In addition to using vim and command line tools, you can also use the Eclipse IDE to write and execute Java programs.

Eclipse can be started from the "Applications->Programming" menu.

Once launched, it will ask you for a "workspace" location to store your programs n your home directory.

Like many IDEs, Eclipse requires having a "project" before you can compile code. Create one from by clicking "File->New->Java Project". It will then ask for a project name and some other settings (the defaults for most are fine).

Then you can add a new Java file by clicking "File->New->File" and entering a file name. Remember that the file name must be the same as the class name.

Then you can copy/paste the Hello World program above into the editor. You can then run the program by clicking "Run->Run" or hitting Ctrl-F11.

You can use either vim and the command line, or Eclipse for you Java programs this semester.

Copyright © 2018 Ian Finlayson | Licensed under a Creative Commons Attribution 4.0 International License.