Switching between Java Versions on Ubuntu linux

If you're using Ubuntu Linux on your daily basis work, you've probably Java installed on your machine. Personally I prefer using Wepupd8 PPA to manage JAVA installation, it makes my life a lot more easier especially for updates. The Wepupd8 team didn’t add any binary for Oracle JAVA installation and they made a script to download the Oracle JAVA from Oracle website and install it straight away. So whenever Oracle will release the update, I can simple upgrade via package manager.

Working with multiple Java versions in your machine is a normal thing, especially if you're a Java developer, and because I'm a (very) lazy person, I'm always looking for a quicker/easier way to make the switch.

Today, I'll share with you my tip on this subject. First, let's run the following command:

$ sudo update-alternatives --config java

Running this command shows a list of installed Java JDKs and JREs allowing one to be selected as the default that is used when java needs to be executed.

There are 5 choices for the alternative java (providing /usr/bin/java).
Selection    Path                                            Priority   Status
------------------------------------------------------------
* 0            /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java   1081      auto mode
  1            /usr/lib/jvm/java-6-oracle/jre/bin/java          1         manual mode
  2            /usr/lib/jvm/java-7-oracle/jre/bin/java          2         manual mode
  3            /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java   1081      manual mode
  4            /usr/lib/jvm/java-8-oracle/jre/bin/java          3         manual mode
  5            /usr/lib/jvm/java-9-oracle/bin/java              4         manual mode

Press <enter> to keep the current choice[*], or type selection number:

But I'm using it just to get the Installation path of each Java version.

Then, for each version I created a script that contain the following lines (in the example below, I'm showing the one for java 8):

sudo update-java-alternatives -s java-8-oracle
export JAVA_HOME=/usr/lib/jvm/java-8-oracle/
export PATH=$PATH:$JAVA_HOME

Note that I'm using u8.sh to make he switch to Java 8, and u9.sh for Java 9 and so on.
The final step is to add an alias in ~/.bashrc file to source our script as follow:

...
# Alias
alias u7='source /home/aboullaite/Utils/Java/u7.sh'
alias u8='source /home/aboullaite/Utils/Java/u8.sh'
alias u9='source /home/aboullaite/Utils/Java/u9.sh'

and That's all. Now for switching between Java versions, I only run u8, u7 or u9 ;)