OpenJDK

How to install Java on Ubuntu, This tutorial is suitable for almost any version of Ubuntu.

如何在 Ubuntu 上安裝 Java,此指引適合幾乎任何 Ubuntu 的版本。

Method 1 : Use the system default version (第一種:系統預設的版本)

Check current java version (檢查目前 java 版本)

$ java -version
Command 'java' not found.

$ update-alternatives --display java
update-alternatives: error: no alternatives for java

Search the version provided by system (搜尋系統預設提供的版本)

$ apt --names-only search "openjdk-.*jdk$"
Sorting... Done
Full Text Search... Done
openjdk-11-jdk/jammy-updates,jammy-security 11.0.19+7~us1-0ubuntu1~22.04.1 amd64
  OpenJDK Development Kit (JDK)

openjdk-17-jdk/jammy-updates,jammy-security 17.0.7+7~us1-0ubuntu1~22.04.2 amd64
  OpenJDK Development Kit (JDK)

openjdk-18-jdk/jammy-updates,jammy-security 18.0.2+9-2~22.04 amd64
  OpenJDK Development Kit (JDK)

openjdk-19-jdk/jammy-updates,jammy-security 19.0.2+7-0ubuntu3~22.04 amd64
  OpenJDK Development Kit (JDK)

openjdk-8-jdk/jammy-updates,jammy-security 8u372-ga~us1-0ubuntu1~22.04 amd64
  OpenJDK Development Kit (JDK)

Install the specified version, such as openjdk-11-jdk (指定版本安裝,例如 openjdk-11-jdk)

$ sudo apt install openjdk-11-jdk

Check the current java version (確認目前 java 版本)

$ java -version
openjdk version "11.0.19" 2023-04-18

$ update-alternatives --display java
java - auto mode
  link best version is /usr/lib/jvm/java-11-openjdk-amd64/bin/java
  link currently points to /usr/lib/jvm/java-11-openjdk-amd64/bin/java
  link java is /usr/bin/java
  slave java.1.gz is /usr/share/man/man1/java.1.gz
/usr/lib/jvm/java-11-openjdk-amd64/bin/java - priority 1111
  slave java.1.gz: /usr/lib/jvm/java-11-openjdk-amd64/man/man1/java.1.gz

Method 2 : OpenJDK manual installation (第二種:OpenJDK 手動安裝)

Please go to the OpenJDK JDK official website to download the specified version, such as OpenJDK JDK 20.0.1 Linux/x64.

請先至 OpenJDK JDK 官方網站 下載指定版本,如 OpenJDK JDK 20.0.1 Linux/x64

Create a self-hosted java directory (建立自託管的 java 目錄)

$ sudo mkdir -p /opt/java

Extract to java directory (解壓縮至 java 目錄)

$ sudo tar -C /opt/java -xf openjdk-20.0.1_linux-x64_bin.tar.gz

Install the specified java (安裝指定的 java 來源)

$ sudo update-alternatives --install /usr/bin/java java /opt/java/jdk-20.0.1/bin/java 100

Confirm whether the installation is successful (確認是否安裝成功)

$ sudo update-alternatives --display java

Config java version (指定目前 java 版本)

$ sudo update-alternatives --config java

Options (補充)

If you want to restore the original system default java version (若要恢復為原本系統預設的 java 版本)

$ sudo update-alternatives --auto java

Or remove (若要移除 java 版本)

$ sudo update-alternatives --remove java /opt/java/jdk-20.0.1/bin/java
$ rm -rf /opt/java/jdk-20.0.1