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.