Switiching Java version per session

I have a combination of Java7 and Java8 installed on my 14.04 machine.

When I want to switch between them I do a sudo update-alternatives --config java. However, changing it this way changes the current Java version on all terminals. I wanted to change it only for the current terminal. For example, I want to test some Java code written in 1.7 against other code, compiled in 1.8.

Another alternative would be doing something like

function java_use() {
   export JAVA_HOME=$(/usr/libexec/java_home -v $1)
   export PATH=$JAVA_HOME/bin:$PATH
   java -version
}

But that works only on my Mac and I wanted something cleaner, without having to modify the PATH every time. Maybe using chroot?

How can I "cleanly" change my Java version - preferably only between the installed versions - and only for the current terminal session?


If you look at /usr/sbin/update-java-alternatives, you'll see it iterates /usr/lib/jvm/.*.jinfo to find the installed versions, so you could do the same for detecting the installed versions.

As for not modifying PATH every time, you can circumvent PATH completely by telling bash which binary it should use for java with the builtin hash command (run help hash).

Here's something you can build on:

java_use() {
    local file version versions=()
    for file in /usr/lib/jvm/.*.jinfo; do
        [[ -e $file ]] || continue
        version=${file##*/.} version=${version%.jinfo}
        versions+=("$version")
    done
    if (( ${#versions[@]} == 0 )); then
        printf >&2 'No java installed\n'
        return 1
    fi
    select version in "${versions[@]}"; do
        if [[ -n $version ]]; then
            export JAVA_HOME="/usr/lib/jvm/$version"
            hash -p "$JAVA_HOME/bin/java" java
            break
        fi
    done
    type java
}