Setting JAVA_HOME on OS X using the java_home tool

OS X has had a very useful utility, since 2003, that allows you to easily generate a path to a JDK.  The simplest usage of the tool will return the default JDK, which in my case is update 17 of JDK 1.7.

➜ ~ /usr/libexec/java_home 

You can also ask it to list all of your JDKs too by using the -V argument.  I have omitted the JDK paths for brevity.

➜ ~ /usr/libexec/java_home -V
Matching Java Virtual Machines (5):
 1.7.0_17, x86_64: "Java SE 7" 
 1.6.0_43-b01-447, x86_64: "Java SE 6" 
 1.6.0_43-b01-447, i386: "Java SE 6" 
 1.6.0_33-b03-424, x86_64: "Java SE 6" 
 1.6.0_33-b03-424, i386: "Java SE 6"

You can also do some cool stuff like filter by cpu architecture:

➜ ~ /usr/libexec/java_home -a i386
➜ ~ /usr/libexec/java_home -a x86_64

If that’s a bit wordy for you you can do the same thing by specifying the data model (bits) too:

➜ ~ /usr/libexec/java_home -d 32
➜ ~ /usr/libexec/java_home -d 64

The tool can do some other stuff too and the manual page is clear and concise.

This helps us because we can simply do something like this in our shell configuration files to make JAVA_HOME always point to the latest JDK by default.

export JAVA_HOME=`/usr/libexec/java_home`

This line would typically go in ~/.bashrc if you use bash or ~/.zshrc if you use zsh.  You can also put it in /etc/profile if you want it to be available to all users and not just yourself.

Naturally if you don’t want to use the latest and greatest you could specify that you want to use the 64-bit JDK 1.6 like this:

export JAVA_HOME=`/usr/libexec/java_home -d 64 -v "1.6*"`

The back-ticks, `, in the command are important.  They capture the output of the java_home command and then that value is assigned to the JAVA_HOME environmental variable.  Finally this variable is exported, meaning it will be available to sub-processes.

Do note that the variable will not be available in GUI programs but I’m going to cover that in a later series of posts about setting up an Mavenised Android build environment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s