< Irrelevant.dev

Easiest Way to Manage JDKs on OSX

Published On: March 29, 2022 🌭?
Java OSX CLI

Assumes Homebrew has been installed

Tap and Install JDK(s)

brew tap mdogan/zulu
brew install zulu-jdk8
brew install zulu-jdk11
brew install zulu-jdk18

Github for Cask

Verify JDK(s) are Registered

/usr/libexec/java_home -V

You should see some output like:

18 (x86_64) "Azul Systems, Inc." - "Zulu 18.28.13" /Library/Java/JavaVirtualMachines/zulu-18.jdk/Contents/Home
11.0.14 (x86_64) "Azul Systems, Inc." - "Zulu 11.54.23" /Library/Java/JavaVirtualMachines/zulu-11.jdk/Contents/Home

Setup Script to Switch JDKs

In your .bashrc/.zshrc (or equivalent shell config) add the following aliases, and then call the one you want as your default:

alias jdk8='unset JAVA_HOME;export JAVA_HOME=`/usr/libexec/java_home -v 1.8.0`;echo $JAVA_HOME;java -version;'
alias jdk11='unset JAVA_HOME;export JAVA_HOME=`/usr/libexec/java_home -v 11`;echo $JAVA_HOME;java -version;'
alias jdk18='unset JAVA_HOME;export JAVA_HOME=`/usr/libexec/java_home -v 18`;echo $JAVA_HOME;java -version;'
jdk11

From here, you can run jdk8 / jdk11 / jdk18 to switch your java version to the target you want.

How It Works

Setting up JDK(s) on a Mac is not as straightforward as it should be. OSX ships with a proxy app in /usr/bin/java that then runs the java command at wherever $JAVA_HOME points. If $JAVA_HOME is not set, it will run whatever is returned from /usr/libexec/java_home. This misdirection is what has always made setting up an OSX environment odd for me. I'm used to the java on my PATH being the JDK binary, and OSX kind of fights that.

Luckily, the /usr/libexec/java_home utility gives us all the tools we need to wrangle our environment in a sane way. We can list all installed java versions (-V flag), and request the path to any specific version (-v flag).

There are plenty of other ways to handle managing JDKs on OSX. I've tried a good number of them. But this approach is less complex, quicker to setup, and it "just works".