I’m writing quite a bit of Java at the moment. Most of the time I can use Java 7, but unfortunately some must still be written in Java 6 as they need to run on old RedHat servers. Soon, I want to look at Java 8.

But managing different versions of Java has always been a bit of a pain, until I found jEnv.

jEnv allows you to switch to different versions of Java using simple commands. It will be familiar to anyone who has rbenv, plenv, etc.

Install jEnv using Homebrew:

brew install https://raw.github.com/gcuisinier/jenv/homebrew/jenv.rb

You should then add the following to your .bash_profile, or equivalent, to ensure it is always available:

if which jenv > /dev/null; then eval "$(jenv init -)"; fi

Now it’s installed, lets see what versions of Java it can find:

$ jenv versions
* system (set by /Users/ajones/.jenv/version)

For me, it only found the system Java, though I did have others installed. The asterisk is the version currently selected.

Unlike rbenv and friends, jEnv isn’t able to install any versions of Java, so we have to install them ourselves and then point jEnv at them.

To install Java 6, download it from the Apple webiste. It will install to /System/Library/Java/JavaVirtualMachines/. Add it to jEnv with the following:

$ jenv add /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/
oracle64-1.6.0.65 added

Running jenv versions should now show it:

$ jenv versions
* system (set by /Users/ajones/.jenv/version)
  oracle64-1.6.0.65

So far so good. Lets download and install Java 7 from Oracle. This time it is installed in /Library/Java/JavaVirtualMachines/, so use the following to add it to jEnv:

jenv add /Library/Java/JavaVirtualMachines/jdk1.7.0_67.jdk/Contents/Home/

Finally Java 8 can either be installed from Oracle or (better) Homebrew Cask:

brew cask install java

It will be installed to the same place as Java 7, so add it in the same way.

So now we have three different versions of Java installed, lets take a look at how to use them.

To select a version, run jenv local [version], for example:

$ jenv local oracle64-1.6.0.65
$ 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)

You can set a default version using jenv global [version], and show the full path to the Java executable by running jenv which java.

Probably my favourite feature of jEnv is to use a .java-version file to set the version of Java in specific directories. So for projects where I need Java 6, I save a .java-version file with oracle64-1.6.0.65 as the contents, and jEnv will set the local Java version when I enter the directory.

And that’s it. We now have multiple versions of Java and can easily switch between them. jEnv also has some other features, such as wrappers for Gradle, Ant, Maven, etc, and the ability to set JVM options globally or locally. Check out the documentation for more information.