Java powers enterprise applications, build tools like Maven and Gradle, and platforms like Jenkins, Elasticsearch, and Minecraft servers. This guide covers installing OpenJDK, the standard open-source Java implementation.
Prerequisites
- Ubuntu 22.04/24.04 or Debian 11/12 VPS
- Root or sudo access
Step 1 — Install OpenJDK
sudo apt update
sudo apt install default-jdk -y
Or a specific version:
sudo apt install openjdk-21-jdk -y
Step 2 — Verify Installation
java -version
javac -version
Step 3 — Set JAVA_HOME
sudo nano /etc/environment
Add:
JAVA_HOME="/usr/lib/jvm/default-java"
source /etc/environment
echo $JAVA_HOME
Installing Multiple Java Versions
sudo apt install openjdk-17-jdk openjdk-21-jdk -y
Switching Between Java Versions
sudo update-alternatives --config java
Step 4 — Test with a Simple Program
nano HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello from Java!");
}
}
javac HelloWorld.java
java HelloWorld
Installing Maven (Java Build Tool)
sudo apt install maven -y
mvn -version
Installing Gradle (Alternative Build Tool)
sudo apt install gradle -y
gradle -version
Running a Java Application (JAR File)
java -jar myapp.jar
Running a Java Application as a systemd Service
sudo nano /etc/systemd/system/myapp.service
[Unit]
Description=My Java Application
After=network.target
[Service]
ExecStart=/usr/bin/java -jar /opt/myapp/myapp.jar
Restart=always
User=deploy
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now myapp
Common Errors
"java: command not found" — installation failed or PATH isn't updated; verify with which java and reinstall if needed.
Wrong Java version being used — use update-alternatives --config java to select the correct default among installed versions.
Best Practices
- Use OpenJDK for most applications unless a specific product requires Oracle's commercial JDK
- Set
JAVA_HOMEfor build tools and applications that require it - Run production Java applications as a managed systemd service, not a manual foreground process
FAQ
Should I install the JRE or JDK?
Install the JDK — it includes both the runtime (JRE) and development tools, and is the recommended choice for nearly all server use cases, including simply running pre-built applications.
Related Articles
- How to Manage Services with systemd and systemctl
- How to Install Nginx on Ubuntu & Debian
- How to Check VPS Resource Usage (CPU, RAM & Disk)
