Switching Java versions on Mac OS

The Java JDK install on MacOS has some interesting platform specific utilities, like

/usr/libexec/java_home

which tells you which Java version you’re currently using and where it’s installed. I have Java 9 currently installed and it tells me:

/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home

If you have multiple version installed, adding -V will list all the versions and where they’re installed:

$ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
    9, x86_64: "Java SE 9" /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home
    1.8.0_101, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_101.jdk/Contents/Home

The next logical question from here would be ‘how do I switch versions’? If you set your $PATH in a .profile or similar approach, you can eval java_home to add the current version to your path, but a neat trick discussed in one of the answers here (thanks to this SO user for this tip) uses the -v option to allow you to switch versions. Adding a couple of aliases to your .profile like this:

alias j9="export JAVA_HOME=`/usr/libexec/java_home -v 9`; java -version"
alias j8="export JAVA_HOME=`/usr/libexec/java_home -v 1.8`; java -version"
alias j7="export JAVA_HOME=`/usr/libexec/java_home -v 1.7`; java -version"

… and you’ve got a quick shortcut to switching between different versions.

2 Replies to “Switching Java versions on Mac OS”

  1. The aliases do not work for me:
    JARMAC:~ jar$ alias java11=”export JAVA_HOME=/usr/libexec/java_home -v 11; java -version”
    JARMAC:~ jar$ java11
    bash: export: `-v’: not a valid identifier
    bash: export: `11′: not a valid identifier
    Unable to locate an executable at “/usr/libexec/java_home/bin/java” (-1)

  2. It needs back ticks to work:
    JARMAC:~ jar$ alias java10=”export JAVA_HOME=`/usr/libexec/java_home -v 10`; java -version”
    JARMAC:~ jar$ java10
    java version “10” 2018-03-20
    Java(TM) SE Runtime Environment 18.3 (build 10+46)
    Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10+46, mixed mode)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.