How to Install Java 17 on Ubuntu

How to Install Java 17 on Ubuntu

Java and the JVM (Java’s virtual machine) are required for many kinds of software, including Tomcat, Jetty, Glassfish, Cassandra and Jenkins.

In this guide, you will install various versions of the Java Runtime Environment (JRE) and the Java Developer Kit (JDK) using apt. You’ll install OpenJDK as well as the official JDK from Oracle. You’ll then select the version you wish to use for your projects. When you’re finished, you’ll be able to use the JDK to develop software or use the Java Runtime to run software.

Installing Java 17

To install the OpenJDK version of Java, first update your apt package index:

sudo apt update

Execute the following command to install the JRE from OpenJDK 17:

sudo apt install openjdk-17-jre

The JRE will allow you to run almost all Java software.

Verify the installation with:

java -version

You’ll receive output similar to the following:

openjdk 17.0.2 2022-01-18
OpenJDK Runtime Environment (build 17.0.2+8-Ubuntu-120.04)
OpenJDK 64-Bit Server VM (build 17.0.2+8-Ubuntu-120.04, mixed mode, sharing)

You may need the JDK in addition to the JRE in order to compile and run some specific Java-based software. To install the JDK, execute the following command, which will also install the JRE:

sudo apt install openjdk-17-jdk

Verify that the JDK is installed by checking the version of javac, the Java compiler:

javac -version

You’ll see the following output:

javac 17.0.2

Installing Oracle JDK 17

Oracle’s licensing agreement for Java doesn’t allow automatic installation through package managers. To install the Oracle JDK, which is the official version distributed by Oracle, you must create an Oracle account and manually download the JDK to add a new package repository for the version you’d like to use.

Download the Oracle JDK 17 from Oracle website

wget https://download.oracle.com/java/17/latest/jdk-17_linux-x64_bin.tar.gz -P /tmp

Create a directory where the JDK will be installed:

sudo mkdir -p /usr/lib/jvm

Extract the downloaded file to the /usr/lib/jvm directory:

sudo tar -xvf /tmp/jdk-17_linux-x64_bin.tar.gz.tar.gz -C /usr/lib/jvm

To set up the Java alternatives, run the following commands:

sudo update-alternatives --install /usr/bin/java java /usr/lib/jvm/jdk-17.0.7/bin/java 1
sudo update-alternatives --install /usr/bin/javac javac /usr/lib/jvm/jdk-17.0.7/bin/javac 1

If you have more versions of java installed run the following commands to set default java version:

sudo update-alternatives --config java
sudo update-alternatives --config javac

Finally, to verify that Java has been successfully installed, run the following command:

java -version