Managing Multiple JDK on Mac OS X

Recently I had to install the OpenJDK 7 on my Apple MacBook, but keeping the original JDK 6 as my main Java environment. After browsing the Internet I came to a decent set of instructions (Tested with OS X Lion 10.7.3).

In summary:
  1. Get the OpenJDK from (I chose JDK 7u4, which at present seems to be the latest stable build); The JDK 7 is now a regular download by Oracle:
  2. Install the downloaded .dmg package;
  3. Change your Java Preferences accordingly, by moving on top the "OpenJDK 7" item (by default Java SE 6 is the first item - see below picture);
  4. Automatically set the JAVA_HOME variable, so that shell tools work.
To automatically setup the JAVA_HOME variable it's necessary to add few lines to the .profile.
So, edit this file (it's in your home directory) adding the following lines:

# Change your JAVA_HOME
function setjdk() {
if [ $# -ne 0 ];
then export JAVA_HOME=`/usr/libexec/java_home -v $@`;
java -version;
# Automatically set the JAVA_HOME
export JAVA_HOME=`/usr/libexec/java_home`

Note that the optional setjdk function allows for dynamically changing the JAVA_HOME if you switch items in your "Java Preferences", otherwise many Java tools won't work if JAVA_HOME is not in synch with the System settings.

Whenever you change the default JDK using the "Java Preferences" tool, then any new terminal will automatically pick-up the new JAVA_HOME by executing /usr/libexec/java_home, so executing the setjdk function is not usually necessary, unless you really don't want to close and re-open the terminal (opening the terminal reloads the .profile). Alternatively issue the command source .profile in you shell.

That's it, now you can install multiple JDKs and select them dynamically, by just using the "Java Preferences" tool, without touching any system file by hand.