Java is a widely used programming language that is essential for developing and running applications on various platforms. This guide provides a step-by-step process for installing Java on Ubuntu 18.04, 20.04, and 22.04 using the Apt-Get package manager. Additionally, it explains how to switch between different Java versions and set the JAVA_HOME environment variable.
Installation of the Default JRE/JDK
The default JRE and JDK can be installed using the following commands:
apt-get install default-jre
apt-get install default-jdk
The JDK includes the JRE, so you can install the JDK instead of the JRE if you need both.
Installing other Java Versions
Older versions of Java can be installed using the following commands:
apt-get install openjdk-8-jdk -y
apt-get install openjdk-8-jre -y
Replace “8” with the desired Java version, such as 11, 16, or 17.
Switching between different Java Versions
It is possible to have several Java versions installed at the same time, but only one Java version is selected or active at a time.
You can switch between different Java versions using the following command:
sudo update-alternatives --config java
This will display a list of installed Java versions. Select the desired Java version by entering its corresponding number.
How to set the “JAVA_HOME” environment Variable
The JAVA_HOME environment variable points to the root directory of the Java installation. To set the JAVA_HOME variable, follow these steps:
- Run the following command to get the path of the desired Java version:
sudo update-alternatives --config java
- Open the following file:
sudo nano /etc/environment
- Add the following line to the file:
JAVA_HOME="YOUR_PATH"
-
Replace “YOUR_PATH” with the actual path of the Java version.
-
Save the file and close the editor.
-
Reload the configuration file:
source /etc/environment
- Verify that the JAVA_HOME variable is set correctly:
echo $JAVA_HOME
Congrats! Now you know how to install different versions of Java and how to switch between them.
Conclusion
This guide has provided comprehensive instructions for installing and managing Java on Ubuntu 18.04, 20.04, and 22.04. By following these steps, you can easily install the desired Java version, switch between different versions, and set the JAVA_HOME environment variable.