Installing and Managing Multiple Java JDKs on Linux

Recently, Linux has become a friendlier environment for installing and managing alternate JDK environments. This is a short tutorial to demonstrate the best way to manage alternate JDKs.

Listing Installed JDKs

First, you can use the CLI program update-alternatives to manage your Java JDKs:

$ sudo update-alternatives --config java

There are 4 choices for the alternative java (providing /usr/bin/java).

  Selection    Path                                            Priority   Status
------------------------------------------------------------
  0            /usr/lib/jvm/java-11-openjdk-amd64/bin/java      1111      auto mode
  1            /opt/jdk1.8.0_291/bin/java                       1         manual mode
  2            /usr/lib/jvm/java-11-openjdk-amd64/bin/java      1111      manual mode
  3            /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java   1081      manual mode
* 4            /usr/lib/jvm/jdk-11.0.11/bin/java                1         manual mode

Press <enter> to keep the current choice[*], or type selection number:

As you can see, this computer has the Oracle JDK 11 installed in /opt.

Installing a New JDK

Download the JDK of your choice from the desired location. OpenJDK versions can generally be installed via your package manager - apt, rpm, pacman, etc. Oracle JDKs must be downloaded from the Oracle web site.

In the case of an Oracle JDK, once you have downloaded and installed the JDK (I installed JDK 11 via a .deb package on this Ubuntu system), you will need to add it as an optional Java config:

$ sudo update-alternatives --install /usr/bin/java java /usr/lib/jvm/jdk-11.0.11/bin/java 1

You may of course also want to add the Java compiler as an option:

$ sudo update-alternatives --install /usr/bin/javac javac /usr/lib/jvm/jdk-11.0.11/bin/javac 1

Selecting the New JDK

After you have added the entry, just run the config again to set the active Java to the Java of your choice:

$ sudo update-alternatives --config java

Select the JDK you would like to use and you will be ready to roll.

Don’t forget to update your JAVA_HOME environment variable to point to the active JDK. This system is running ZSH, so we’ll update in ~/.zshrc. In .zshsrc, or .bashrc for Bash users, add this line:

export JAVA_HOME=/usr/lib/jvm/jdk-11.0.11

or update the existing JAVA_HOME setting with the location of the new JDK.