Skip to content

Java: Install/Compile/Run

Java Development Kit (JDK)

The Java Development Kit, or JDK, is a development environment for building Java applications. The environment provides a virtual machine to execute compiled Java code (JVM), a collection of classes and libraries, and a set of tools to support development (including a compiler (javac), a debugger (jdb), an interactive shell (jshell)) etc.

There are several variations of JDK available. For instance, OpenJDK is a free and open source version of JDK. GNU offers a compiler in Java (gcj) and Java core libraries in Gnu classpath. Eclipse offers its own version of Java compiler1. These variations are mostly the same, but for the purpose of this module, we will use the official Oracle version.

There are different editions of Java. The main ones are Java SE (standard edition), Java EE (enterprise edition), and Java ME (micro edition). We will be using Java SE.

The latest version of Java SE is Java 9.0.1. Java 8 is the earliest version of Java that will work with this module, as many concepts we will cover are only introduced in Java 8.
To use jshell, however, you need Java 9.

Installing JDK or Java SE 9

You can download the latest version of Java SE 9 from Oracle and follow its installation instructions.

Using apt

An alternative to the Oracle's instructions above, if you are using a Ubuntu-based system, is to use apt. You can do the following:

1
2
3
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java9-installer

The first line asks apt to add Java's PPA (personal package archive) repository to its database. The second line updates the local apt database with the available apt packages. Finally, the last line installs Java 9.

Compiling

Now that you've installed Java on your machine, here's an example of how you can compile and run some Java code.

Java source files

Create a new Java source file and put it in a new folder (e.g. CS2030).

1
2
3
4
5
class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello, world!");
  }
}

By convention, the file should be named HelloWorld.java, following the UpperCamelCase name of the class. At this point, our CS2030 folder only contains that one file.

1
2
happytan@cs2030-i:~[xxx]$ ls
HelloWorld.java

Java class files

We can go ahead and compile our Java program by running the javac HelloWorld.java command. This creates the corresponding Java class file, HelloWorld.class.

1
2
3
happytan@cs2030-i:~[xxx]$ javac HelloWorld.java
happytan@cs2030-i:~[xxx]$ ls
HelloWorld.class HelloWorld.java

We can now execute it with java HelloWorld. Remember to omit the .class extension when doing this!

1
2
happytan@cs2030-i:~[xxx]$ java HelloWorld
Hello, world!

Success! 🎉

What actually happens under the hood? Is Java an interpreted or compiled language?

This can get a little mind-boggling at first, but this diagram summarizes it quite well.