Before diving into the technicalities, it’s important to understand the different Java versions. Oracle releases new versions regularly, and each version may have differences in performance, security, and functionality. Commonly used versions include Java 8 (LTS), Java 11 (LTS), and the latest release at the time of writing.
Step 1: Installing Multiple Java Versions
Ubuntu’s package manager, APT, makes it easy to install multiple Java versions. Here’s how you can do it:
- Update Your Package List: Open a terminal and run:
sudo apt update
- Install Java: You can install multiple Java versions by running:
sudo apt install openjdk-8-jdk openjdk-11-jdk
Replace 8 and 11 with the versions you need.
Step 2: Verifying Java Installation
- After installation, verify by running:
java -version
- This command shows the default Java version. To list all installed Java versions, run:
update-java-alternatives -l
Step 3: Switching Java Versions
To switch Java versions, use the update-alternatives command:
sudo update-alternatives --config java
This command lists all installed Java versions and lets you choose the default version by entering the selection number.
Step 4: Setting JAVA_HOME Environment Variable
Many applications require the JAVA_HOME environment variable. Set this by editing your profile settings:
- Open your profile script: Edit ~/.bashrc or ~/.zshrc, depending on your shell.
nano ~/.bashrc
- Add the following line at the end:
export JAVA_HOME=$(dirname $(dirname $(readlink -f $(which java))))
- Save and close the file.
- Apply the changes:
source ~/.bashrc
[OR]source ~/.zshrc
Using SDKMAN for Advanced Java Management
For more advanced Java version management, consider using SDKMAN, a tool that simplifies installing and switching between different SDKs:
- Install SDKMAN: We can quickly install skdman using the following command:
curl -s "https://get.sdkman.io" | bash
- Update Environment: Open a new terminal or source the SDKMAN scripts
source "$HOME/.sdkman/bin/sdkman-init.sh"
- Install Java Versions: Use sdk command to install a specific Java version:
sdk install java 11.0.2-open
- Switch Java Versions: You can switch to any Java version anytime with the following command. Just replace the version you want to set as default java version:
sdk use java 11.0.2-open
Conclusion
Managing multiple Java versions on Ubuntu doesn’t have to be a daunting task. With the right tools and commands, you can easily switch between versions, ensuring compatibility and efficiency in your development workflow. Whether you’re a beginner or an experienced developer, these steps will help you maintain a flexible and productive Java environment on Ubuntu.
Further Reading and Resources:
Ubuntu Documentation: https://ubuntu.com/server/docs
Java Development Kit: https://jdk.java.net/
SDKMAN: https://sdkman.io/
With this guide, you’re now equipped to manage multiple Java versions on your Ubuntu system effortlessly. Happy coding!