Many modern programs require Java to run. From development tools like Eclipse to search systems like Elasticsearch, Java is a core package for web hosts.
There are different versions of Java available. You can use OpenJDK, which is the open source version, or the official Oracle Java. For almost all tasks, OpenJDK is the best choice because it is free to use and easy to install.
This tutorial will show you how to install Java on Ubuntu 18.04, choose a default version, and set up your system environment.
The default Java version in Ubuntu 18.04 is OpenJDK 11. This version is a long-term support release and is the standard for most modern systems.
Open your terminal and update the package list:
bashsudo apt update
Install the full development kit by running:
bashsudo apt install default-jdk
Verify that the installation was successful:
bashjava -version
The output will display the installed Java version. If you only need to run Java apps and do not need to build them, you can install the runtime environment instead by running sudo apt install default-jre.
Some older programs do not work with newer Java versions. If you run software that requires Java 8, you can install OpenJDK 8 on the same machine.
Update your package index and run this install command:
bashsudo apt updatesudo apt install openjdk-8-jdk
Confirm the installation by checking the version again:
bashjava -version
The output will show version 1.8.0 to confirm that the package was installed correctly.
If you have both Java 11 and Java 8 on your server, you can choose which one the system uses by default.
Run the configuration tool:
bashsudo update-alternatives --config java
The terminal will print a list of all installed Java versions. Each version has a number next to it. Type the selection number for the version you want to use and press Enter.
Many Java programs look for the JAVA_HOME variable to find where Java is installed.
First, locate the path of your default Java version using the configuration command from the previous section. Copy the path to the directory, leaving out the /bin/java part.
Open the system environment file:
bashsudo nano /etc/environment
Add the following line at the end of the file:
textJAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64"
Save your changes. Reload the file to apply the environment changes to your current session:
bashsource /etc/environment
Confirm the path by printing the variable:
bashecho $JAVA_HOME
You have installed Java and set up your system path. Now you can run Java apps or start building your own. If you have any questions about this guide, leave a comment below.