Quickly switch Java versions on macOS

Inspired by a Jfokus session I attended today I decided to download and install a preview of Java 9 on my MacBook. That went pretty quick and without much trouble. But when I issued java -version on my terminal, I was greeted with

Java(TM) SE Runtime Environment (build 9-ea+155)
Java HotSpot(TM) 64-Bit Server VM (build 9-ea+155, mixed mode)

Although that’s nice - you’d even expect it, maybe - I realised I often need Java 8 as well. How to quickly switch between the two?

I ended up with three aliases in my ~/.zshrc:

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"

Now I can rapidly switch between the three versions I have installed, and I will even get immediate feedback as to whether that succeeded:

j9
java version "9-ea"
Java(TM) SE Runtime Environment (build 9-ea+155)
Java HotSpot(TM) 64-Bit Server VM (build 9-ea+155, mixed mode)

Neat!