Easily switching between Java versions on OS X

If you’re a Java developer you’re probably familiar with the problems caused by sometimes having to switch between Java versions. At least on OS X there is no straightforward way of doing this. A typical use case for me these days is that Java 7 is used most of the time and once in a while I switch to Java 8 for playing with the new features.

So in order to make this easier I added a few aliases and functions to my .profile. The following allows you to easily switch between Java 6, 7 and 8 simply by issuing j6, j7 or j8 respectively on the command line. You may also use the command jls in order to list all available Java versions. The script is written for OS X, but can possibly be adapted to work on other operating systems.

# Java settings
alias j6='ju 1.6'
alias j7='ju 1.7'
alias j8='ju 1.8'

function jls() {
  echo "Use ´j6, j7 and j8´ to conveniently switch between Java versions."
  echo "For a specific version use ´ju <version>´ where available versions are listed below:"
  /usr/libexec/java_home -V 2>&1 | grep -E "\d.\d.\d" | cut -d , -f 1 | colrm 1 4 | grep -v Home
}

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