I’m doing this on Ubuntu 20.04 but it should work on any modern-ish Ubuntu or other Debian Linux.
In this scenario, you have already installed “default-jdk” or “default-jre” (which is version 11 on Ubuntu 20.04) and have a working Java installation, and now you want to use a different java version (in my case, I wanted version 16).
First find the java version you want to use:
apt-cache search openjdk
You’re looking for something in the list that looks like openjdk-version-jdk or openjdk-version-jre. In my case I wanted openjdk-16-jdk
Install your desired jdk or jre chosen from the search list:
sudo apt install openjdk-whatever-version
Check the java alternatives list to get the path to your new java version:
My list looks like this:
java-1.11.0-openjdk-amd64 1111 /usr/lib/jvm/java-1.11.0-openjdk-amd64
java-1.16.0-openjdk-amd64 1611 /usr/lib/jvm/java-1.16.0-openjdk-amd64
So in my case, the path I would use in the next command is /usr/lib/jvm/java-1.16.0-openjdk-amd64. Use the path to set the new java version
sudo update-java-alternatives --set /path/to/java/version
If you’re using just the jre and not the full jdk you’ll get a bunch of “alternative not registered” errors. I this case, you can add the –jre flag to limit the action to just the jre-related stuff.
sudo update-java-alternatives --jre --set /path/to/java/version
Verify you are now using the desired java version:
That’s it. Have fun.