Ubuntu: Switch between multiple java versions


While installing Android Studio on Ubuntu 14.04 I get the message that my Java version (javac 1.7.0_79) is causing problems. I found a solution of how to install a newer Oracle version of Java:

sudo apt-add-repository ppa:webupd8team/java  sudo apt-get update  sudo apt-get install oracle-java8-installer  

However I'm afraid that this might overwrite my existing open-jdk version of Java. Since I don't know which of my programs depend on Java, I fear that this could crash these other programs.

Is there a way to make sure apt-get doesn't overwrite my previous Java? I would basically like to have installed both and be able to switch between them manually, depending on what version I need.


Apt-get won't overwrite the existing java versions.

To switch between installed java versions, use the update-java-alternatives command.

List all java versions:

update-java-alternatives --list  

Set java version as default (needs root permissions):

sudo update-java-alternatives --set /path/to/java/version  

...where /path/to/java/version is one of those listed by the previous command (e.g. /usr/lib/jvm/java-7-openjdk-amd64).

Additional information:

update-java-alternatives is a convenience tool that uses Debian's alternatives system (update-alternatives) to set a bunch of links to the specified java version (e.g. java, javac, ...).



sudo update-alternatives --config java  

which lists all installed versions with current active one marked and provides dialog to switch:

There are 3 choices for the alternative java (providing /usr/bin/java).    Selection    Path...  ------------------------------------------------------------    0            /usr/lib/jvm/java-9-oracle/bin/java...  * 1            /usr/lib/jvm/java-7-oracle/jre/bin/java...    2            /usr/lib/jvm/java-8-oracle/jre/bin/java...    3            /usr/lib/jvm/java-9-oracle/bin/java...    Press <enter> to keep...[*], or type selection number:   


export JAVA_HOME="$(jrunscript -e 'java.lang.System.out.println(java.lang.System.getProperty("java.home"));')"  

to set $JAVA_HOME from current active version


Based on the answer from @muet, I found this to work seamlessly:

Add this to ~/.bashrc:

export JAVA_HOME="$(jrunscript -e 'java.lang.System.out.println(java.lang.System.getProperty("java.home"));')"  

Add to aliases:

alias useJava8='yes | sudo apt-get install oracle-java8-set-default && source ~/.bashrc'  alias useJava7='yes | sudo apt-get install oracle-java7-set-default && source ~/.bashrc'  

Then you can switch within the same shell using only: useJava7or useJava8

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »