How can I select which Java to use?

I have installed both OpenJDK 6 and 7. When I run "java somefile" from the command line, OpenJDK 6 is invoked. I do not want to change this default behavior. What command can I use to run my non-default OpenJDK 7 installation instead?

(I am used to running "python somefile" to invoke the default Python, "python2.7 somefile" to use Python 2.7 specifically and "python3 somefile" to use Python 3 specifically.)


Solution 1:

You can select java version using update-alternatives command.

Run below command in terminal.

sudo update-alternatives --config java

And type selection number that you want to use.

Like this:

selecting java version

Caution: The above description is the procedures for changing a default version. It is not an answer of this question, but it leaves for reference.

Solution 2:

You could bind an alias to the specific java versions. Just add the following lines to your $HOME/.bashrc:

alias java6='/path/to/java6/bin/java'
alias java7='/path/to/java7/bin/java'

Same for javac and you should be fine ;-)

Solution 3:

There is also a frontend to update-alternatives that updates all of the things related to Java:

$ update-java-alternatives -l
java-1.11.0-openjdk-amd64      1111       /usr/lib/jvm/java-1.11.0-openjdk-amd64
java-1.17.0-openjdk-amd64      1711       /usr/lib/jvm/java-1.17.0-openjdk-amd64
java -version
$ java -version
openjdk version "17" 2021-09-14
OpenJDK Runtime Environment (build 17+35-Ubuntu-121.04)
OpenJDK 64-Bit Server VM (build 17+35-Ubuntu-121.04, mixed mode, sharing)
$ sudo update-java-alternatives -s java-1.11.0-openjdk-amd64
[sudo] password for user:
$ java -version
openjdk version "11.0.11" 2021-04-20
OpenJDK Runtime Environment (build 11.0.11+9-Ubuntu-0ubuntu2)
OpenJDK 64-Bit Server VM (build 11.0.11+9-Ubuntu-0ubuntu2, mixed mode, sharing)