"java: command not found" on Linux β€” Causes and Fixes

"java: command not found" on Linux means either Java is not installed, or it is installed but not on the $PATH. The fix is usually one of three things: install Java, add the binary to PATH, or reload your shell config.

Step 1: Check if Java is installed at all

which java
type java
find /usr/lib/jvm -name "java" 2>/dev/null | head -5

If find returns something, Java is installed but not on PATH. If it returns nothing, Java is not installed.

Step 2: Install Java (if not installed)

Ubuntu/Debian:

sudo apt update && sudo apt install openjdk-21-jdk -y

Fedora/RHEL:

sudo dnf install java-21-openjdk-devel -y

Arch:

sudo pacman -S jdk-openjdk

After install, open a new shell (or run hash -r / source ~/.bashrc) and retry java -version.

Step 3: Fix PATH if Java is installed but not found

Find the Java binary:

find /usr/lib/jvm /opt -name "java" -type f 2>/dev/null

Add its bin directory to PATH. Edit ~/.bashrc (or ~/.zshrc if you use zsh):

export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64   # adjust path
export PATH=$JAVA_HOME/bin:$PATH

Reload: source ~/.bashrc and test: java -version.

Step 4: If the error appears only in a script or cron

Scripts and cron jobs run with a minimal PATH that often does not include /usr/bin or custom Java directories. Fix by using the full path in your script:

#!/bin/bash
export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64
export PATH=$JAVA_HOME/bin:$PATH
java -jar myapp.jar

Or use the absolute path directly: /usr/lib/jvm/java-21-openjdk-amd64/bin/java -jar myapp.jar.

Step 5: update-alternatives not configured

On systems with multiple JDKs, the alternatives system may not have a default set:

sudo update-alternatives --install /usr/bin/java java \
    /usr/lib/jvm/java-21-openjdk-amd64/bin/java 2100

sudo update-alternatives --install /usr/bin/javac javac \
    /usr/lib/jvm/java-21-openjdk-amd64/bin/javac 2100

# Verify
java -version

Quick diagnostic checklist

  1. which java β€” empty? Not on PATH.
  2. echo $PATH β€” does it contain a jvm directory? If not, PATH is wrong.
  3. java -version β€” still fails after PATH fix? Check you reloaded the shell (source ~/.bashrc).
  4. Running as a different user (root, www-data)? That user may have a different PATH.