I do a lot of development using Java 7 and recently needed to start using Java 8.

The quickest way I know to update to the latest Java uses homebrew:


brew tap caskroom/cask
brew install brew-cask
brew cask install java

I now need an easy way to switch back and forth between Java 7 & 8.

Adding this to your ~/.bash_profile or ~/.profile does the trick:


function setjdk() {
if [ $# -ne 0 ]; then
removeFromPath '/System/Library/Frameworks/JavaVM.framework/Home/bin'
if [ -n "${JAVA_HOME+x}" ]; then
removeFromPath $JAVA_HOME
fi
export JAVA_HOME=`/usr/libexec/java_home -v $@`
export PATH=$JAVA_HOME/bin:$PATH
fi
}
function removeFromPath() {
export PATH=$(echo $PATH | sed -E -e "s;:$1;;" -e "s;$1:?;;")
}

# set your default version
setjdk 1.7

Source.

This script cunningly uses /usr/libexec/java_home -v x.y to do the hard lifting.

I can now easily swap between Java versions as seen below:


david$ setjdk 1.6
david$ java -version
java version "1.6.0_65"
Java(TM) SE Runtime Environment (build 1.6.0_65-b14-462-11M4609)
Java HotSpot(TM) 64-Bit Server VM (build 20.65-b04-462, mixed mode)

david$ setjdk 1.7
david$ java -version
java version "1.7.0_71"
Java(TM) SE Runtime Environment (build 1.7.0_71-b14)
Java HotSpot(TM) 64-Bit Server VM (build 24.71-b01, mixed mode)

david$ setjdk 1.8
david$ java -version
java version "1.8.0_51"
Java(TM) SE Runtime Environment (build 1.8.0_51-b16)
Java HotSpot(TM) 64-Bit Server VM (build 25.51-b03, mixed mode)

This is a nice simple way to swap versions and is at least good enough for now.

Aside: I also tried out jenv which promises much, but wouldn't accept my versions of Java when I tried it out.