In this guide, we’ll walk you through how to install Java on any major Linux distribution.
We will cover
- How to check if Java is already installed
- Installing OpenJDK via package manager
- Installing Oracle JDK manually
- Setting JAVA_HOME and updating PATH
- Verifying installation with Java programs
Step 1: Check if Java is Already Installed
Before you install anything, it's good practice to check whether Java is already on your system.
java -version
Command 'java' not found, but can be installed with:
sudo apt install default-jre
If you see something like the above message, Java isn’t currently installed. If Java is installed, you'll see an output like this:
openjdk version "17.0.8" 2023-07-18
OpenJDK Runtime Environment (build 17.0.8+7-Ubuntu-222.04)
OpenJDK 64-Bit Server VM (build 17.0.8+7-Ubuntu-222.04, mixed mode, sharing)
Step 2: Install OpenJDK (Recommended for Most Users)
OpenJDK is the open-source implementation of Java. It is stable, secure, and available directly through most Linux package managers.
Open a terminal and run the following commands based on your Linux distribution.
For Ubuntu/Debian:
sudo apt update
sudo apt install default-jdk
For Fedora:
sudo dnf install java-17-openjdk-devel
For Arch Linux:
sudo pacman -S jdk-openjdk
After installation, confirm the Java version:
java -version
openjdk version "17.0.8" 2023-07-18
Step 3: Install Oracle JDK (Optional)
If your project specifically requires Oracle JDK, you can download and install it manually. Oracle JDK includes some commercial features and licensing considerations.
Download and Extract Oracle JDK
Go to the official Oracle JDK downloads page and download the appropriate version for Linux. Then run:
cd ~/Downloads
tar -xvf jdk-21_linux-x64_bin.tar.gz
sudo mv jdk-21 /usr/lib/jvm/jdk-21
Configure Oracle JDK as Default
sudo update-alternatives --install /usr/bin/java java /usr/lib/jvm/jdk-21/bin/java 1
sudo update-alternatives --config java
Step 4: Set JAVA_HOME and Update PATH
It's important to let your system know where Java is located. To do this, follow these steps:
1. Open the terminal and edit the shell configuration file
Use any text editor to open your shell configuration file. Use the command based on your shell:
For bash users:
nano ~/.bashrc
For zsh users:
nano ~/.zshrc
2. Add the following lines at the end of the file:
export JAVA_HOME=/usr/lib/jvm/jdk-21
export PATH=$JAVA_HOME/bin:$PATH
3. Save and close the file
In nano, press Ctrl + O
to save, then Ctrl + X
to exit.
4. Apply the changes
Run the following command to apply the changes immediately:
For bash users:
source ~/.bashrc
For zsh users:
source ~/.zshrc
Step 5: Test Java Installation
Let’s test our installation with a simple Hello World program:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, Java on Linux!");
}
}
Compile:
javac HelloWorld.java
Run:
java HelloWorld
Hello, Java on Linux!
If you see this output, your Java installation is working perfectly!