Easily switch between java versions using alternatives in Linux

This approach works in several distros, I’ve been using it in Ubuntu for a while and just used it in Fedora as well.
As a developer, you might need to switch between java versions often, this approach will come in handy then.
We will be using the command “alternatives”, in this case to check the configuration of your Java installation. The default is most often OpenJDK, while you might need Oracle Java.
Run “alternatives –display java” to see which versions you can currently choose from:
[code gutter=”false”]
[joris@today ~]$ alternatives –display java
java – status is manual.
link currently points to /usr/java/latest/bin/java
Current `best’ version is /usr/lib/jvm/java-1.8.0-openjdk-
[joris@today ~]$
There’s no Oracle Java yet, make sure you’ve installed Oracle Java. If you haven’t, you can check this blog post: Install Oracle Java in Fedora, Red Hat or CentOS using Yum and RPM
When Oracle Java is installed, you can add it to your alternatives: “sudo alternatives –install /usr/bin/java java /usr/java/latest/bin/java 20000”
Please note: I used “latest” in the command above, another options is to specifically set the version you want. This way you can install several JDK’s and switch as shown below.
When that is finished, you can select your current flavour of Java:
[code gutter=”false”]
[joris@today ~]$ sudo alternatives –config java
There are 2 programs which provide ‘java’.
Selection Command
* 1 /usr/lib/jvm/java-1.8.0-openjdk-
+ 2 /usr/java/latest/bin/java
Enter to keep the current selection[+], or type selection number:
Choose the option you want to switch between Java versions.
As mentioned by enkouyami, please check if you need to use update-java-alternatives instead of alternatives. The use of alternatives was valid when I wrote the post, but might not be working anymore!

3 Replies to “Easily switch between java versions using alternatives in Linux”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.