In this tutorial, we show you how to set $JAVA_HOME environment variable on latest or older Mac OSX.
1. Mac OSX 10.5 or later
$ vim .bash_profile
export JAVA_HOME=$(/usr/libexec/java_home)
$ source .bash_profile
$ echo $JAVA_HOME
/Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home
Why /usr/libexec/java_home?
This java_home can return the Java version specified in Java Preferences for the current user.
2.Older Mac OSX
For older Mac OSX, the /usr/libexec/java_home doesn’t exists, so, you should set JAVA_HOME to the fixed path :
$ vim .bash_profile
export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home
$ source .bash_profile
$ echo $JAVA_HOME
/System/Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home