Use certain version of JRE / JDK for certain programs

ArchLinux keeps the different JDKs in the /usr/lib/jvm directory, changing the default JDK is a matter of modifying the symbolic links there:

# ls -al /usr/lib/jvm  
lrwxrwxrwx   1 root root     14 May 31 19:58 default -> java-8-openjdk
lrwxrwxrwx   1 root root     18 May 31 19:58 default-runtime -> java-8-openjdk/jre
drwxr-xr-x   7 root root   4096 May 27 21:45 java-10-openjdk
drwxr-xr-x   6 root root   4096 May 31 14:35 java-8-openjdk
drwxr-xr-x   7 root root   4096 May 31 19:56 java-9-openjdk

Arch has a special script for that:

# archlinux-java set java-10-openjdk

and you get:

# java -version
openjdk version "10.0.1" 2018-04-17
OpenJDK Runtime Environment (build 10.0.1+10)
OpenJDK 64-Bit Server VM (build 10.0.1+10, mixed mode)

you can also use the 'fix' and 'status' options:

# archlinux-java fix
# archlinux-java status
Available Java environments:
  java-10-openjdk (default)
  java-8-openjdk
  java-9-openjdk

If I want to use a different version of Java I do two things:

  • First, set JAVA_HOME as appropriate for that installation of Java and export it.
  • Then, update my path with `PATH=${JAVA_HOME}/bin:${PATH}.

Due to the way the PATH is searched, if you add to end of the path, the new version won't be used. Anything added to the end of the path only adds new commands, it does not replace existing commands. Prepending to the PATH variable will use command in the new directory in preference to other command.

Commands like java often involve a number of symbolic links before you get to the program. Using ${JAVA_HOME}/bin bypasses any indirections, and provides a direct path to the various Java related commands.

EDIT: If you want to run only certain programs with a different version of Java you could use a wrapper like this:

#!/bin/bash
# javawrapper - replace Java for a command.
export JAVA_HOME=$1; shift
PATH=${JAVA_HOME}/bin:$PATH
$*

You can then call the wrapper with a command like.

javawrapper /opt/java6 PyCharm

You could also add an alias to your ~/.bashrc file like this

alias PyCharm='javawrapper /opt/java6 PyCharm'