Compile and Run Java 9 Code using Docker

Compile and Run Java 9 Code using Docker

Java 9 is scheduled to release on September 21. If you want to try Java 9 early-access builds now, you can download them from and install them locally. However, installing the Java 9 builds makes them the default JDK in your machine, which may affect other applications that depend on the JDK. A better choice is to use Docker. If you don't have Docker installed, download and install it from

The Docker image we are going to use is the official Apache Maven image which supports Java 9. We use the tag 3.5.0-jdk-9 to get the Maven 3.5.0 with JDK 9.

Check the Java version

Let's first check the Java version. docker run runs a Docker image. Below are the options used in docker run.

  • -i : Keep STDIN open even if not attached
  • -t : Allocate a pseudo-tty
  • --rm : Clean up the container and remove the file system when the container exits
  • --name : Name of the container

maven:3.5-jdk-9 is the Docker image to run. java -version is the command to run inside of the container.

$ docker run -it --rm --name maven-java9 \
  maven:3.5-jdk-9 java -version

The build number is 170.

openjdk version "9-Debian"
OpenJDK Runtime Environment (build 9-Debian+0-9b170-2)
OpenJDK 64-Bit Server VM (build 9-Debian+0-9b170-2, mixed mode)

Java code

Below is the classical Hello World example. The java class Main uses the new collection factory method List.of in Java 9.

package demo;

import java.util.List;

public class Main {
  public static void main(String[] args) {
      List.of("Hello", "World").stream().collect(Collectors.joining(" ")));


Now we can use javac to compile the source file. Here we have more options in docker run.

  • -v: Mount a volume from the host machine to the container
  • -w: Set the working directory inside the container

javac demo/ -d classes is the command to compile the source file into the directory classes.

$ docker run -it --rm --name maven-java9 \
  -v "$PWD":/usr/src/java9 \
  -w /usr/src/java9 maven:3.5-jdk-9 \
  javac demo/ -d classes


Now we can run the Java code using java -cp classes demo.Main. Hello World should be printed to the console.

$ docker run -it --rm --name maven-java9 \
  -v "$PWD":/usr/src/java9 \
  -w /usr/src/java9 maven:3.5-jdk-9 \
  java -cp classes demo.Main
© 2023 VividCode